spring緩存cache的使用詳解

spring緩存cache的使用

在spring配置文件中添加schema和spring對緩存註解的支持:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:cache="http://www.springframework.org/schema/cache"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-3.0.xsd
           http://www.springframework.org/schema/mvc
          http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
            http://www.springframework.org/schema/aop
            http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
            http://www.springframework.org/schema/tx
            http://www.springframework.org/schema/tx/spring-tx.xsd
            http://www.springframework.org/schema/cache
            http://www.springframework.org/schema/cache/spring-cache.xsd"
       default-autowire="byName">
    <!--緩存配置-->
    <cache:annotation-driven/>

在spring配置文件中加入緩存管理器:

    <!-- generic cache manager -->
    <bean id="cacheManager"
          class="org.springframework.cache.support.SimpleCacheManager">
        <property name="caches">
            <set>
                <bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean"
                      p:name="hardwareCache"/>
                      <bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean" 
                      p:name="bannerCache"/>
            </set>
        </property>
    </bean>

然後在代碼的service的impl層加上如下註解即可把數據緩存起來:

@Cacheable(value="bannerCache")

其中@Cacheable表示spring將緩存該方法獲取到的數據,(緩存是基於key-value方式實現的),key為該方法的參數,value為返回的數據,當你連續訪問該方法時你會發現隻有第一次會訪問數據庫. 其他次數隻是查詢緩存.減輕瞭數據庫的壓力.

這裡寫圖片描述

當更新瞭數據庫的數據,需要讓緩存失效時,使用下面的註解:

這個註解表示讓appCache緩存的所有數據都失效。

@CacheEvict(value = "appCache", allEntries = true)

這裡寫圖片描述

springcache配置緩存存活時間

Spring Cache @Cacheable本身不支持key expiration的設置,以下代碼可自定義實現Spring Cache的expiration,針對Redis、SpringBoot2.0。

直接上代碼:

@Service
@Configuration
public class CustomCacheMng{
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    // 指明自定義cacheManager的bean name
    @Cacheable(value = "test",key = "'obj1'",cacheManager = "customCacheManager")
    public User cache1(){
        User user = new User().setId(1);
        logger.info("1");
        return user;
    }
    @Cacheable(value = "test",key = "'obj2'")
    public User cache2(){
        User user = new User().setId(1);
        logger.info("2");
        return user;
    }
    
    // 自定義的cacheManager,實現存活2天
    @Bean(name = "customCacheManager")
    public CacheManager cacheManager(
            RedisTemplate<?, ?> redisTemplate) {
        RedisCacheWriter writer = RedisCacheWriter.lockingRedisCacheWriter(redisTemplate.getConnectionFactory());
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofDays(2));
        return new RedisCacheManager(writer, config);
    }
    
    // 提供默認的cacheManager,應用於全局
    @Bean
    @Primary
    public CacheManager defaultCacheManager(
            RedisTemplate<?, ?> redisTemplate) {
        RedisCacheWriter writer = RedisCacheWriter.lockingRedisCacheWriter(redisTemplate.getConnectionFactory());
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
        return new RedisCacheManager(writer, config);
    }
}

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。

推薦閱讀: