springboot註解方式使用redis緩存

引入依賴庫

在pom中引入依賴庫,以下redis

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
</dependency>

註解使用

@Cacheable

@Cacheable("product")
@Cacheable(value = {"product","order"}, key = "#root.targetClass+'-'+#id")
@Cacheable(value = "product", key = "#root.targetClass+'-'+#id")
自定義cacheManager
@Cacheable(value = "product", key = "#root.targetClass+'-'+#id」 cacheManager="cacheManager")
@CachePut
應用到寫數據的方法上,如新增/修改方法
@CachePut(value = "product", key = "#root.targetClass+'-'+#product.id")
@CacheEvict 
即應用到移除數據的方法上,如刪除方法
@CacheEvict(value = "product", key = "#root.targetClass+'-'+#id")
提供的SpEL上下文數據

Spring Cache提供了一些供咱們使用的SpEL上下文數據,下表直接摘自Spring官方文檔:spring

名字 位置 描述 示例
methodName root對象 當前被調用的方法名 #root.methodName
method root對象 當前被調用的方法 #root.method.name
target root對象 當前被調用的目標對象 #root.target
targetClass root對象 當前被調用的目標對象類 #root.targetClass
args root對象 當前被調用的方法的參數列表 #root.args[0]
caches root對象 當前方法調用使用的緩存列表(如@Cacheable(value={"cache1", "cache2"})),則有兩個cache #root.caches[0].name
argument name 執行上下文 當前被調用的方法的參數,如findById(Long id),咱們能夠經過#id拿到參數 #user.id
result 執行上下文 方法執行後的返回值(僅當方法執行以後的判斷有效,如‘unless’,'cache evict'的beforeInvocation=false) #result

自定義Cache配置

@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
    /**
    * 自定義redis key值生成策略
    */
    @Bean
    @Override
    public KeyGenerator keyGenerator() {
        return (target, method, params) -> {
            StringBuilder sb = new StringBuilder();
            sb.append(target.getClass().getName());
            sb.append(method.getName());
            for (Object obj : params) {
                sb.append(obj.toString());
            }
            return sb.toString();
        };
    }
    
    @Bean
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
      ObjectMapper om = new ObjectMapper();
      om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
      om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
      //redis序列化
      Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
      jackson2JsonRedisSerializer.setObjectMapper(om);

      StringRedisTemplate template = new StringRedisTemplate(factory);
      template.setValueSerializer(jackson2JsonRedisSerializer);
      template.afterPropertiesSet();
      return template;
    }

    /**
    * 自定義CacheManager
    */
    @Bean
     public CacheManager cacheManager(RedisTemplate redisTemplate) {
         //全局redis緩存過時時間
         RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofDays(1));  
         RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisTemplate.getConnectionFactory());
        return new RedisCacheManager(redisCacheWriter, redisCacheConfiguration);
    }
}
相關文章
相關標籤/搜索