SpringCache实现缓存

依赖

无需指定版本

 <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-pool2</artifactId>
</dependency>

yml配置

可选择使用lettuce或者jedis

spring:
  cache:
    type: redis
  redis:
    database: 0
    host: localhost
#    password: ''
    port: 6379
    client-type: lettuce
#    jedis:
#      pool:
#        #最大连接数据库连接数,0 为没有限制
#        max-active: 8
#        #最大等待连接中的数量,0 为没有限制
#        max-idle: 8
#        #最大建立连接等待时间。如果超过此时间将接到异常。设为-1表示无限制。
#        max-wait: -1ms
#        #最小等待连接中的数量,0 为没有限制
#        min-idle: 0
    lettuce:
      pool:
        max-active: 8
        max-idle: 8
        max-wait: 10000
        min-idle: 0
      shutdown-timeout: 100

RedisConfig配置类,配置缓存规则

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.util.StringUtils;
import java.lang.reflect.Method;
import java.time.Duration;

@Configuration
public class RedisConfig<K,V> {
//配置操作类,可以用来手动操作redis
    @Bean
    public RedisTemplate<K,V> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<K,V> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(factory);
        // 使用Jackson2JsonRedisSerialize 替换默认序列化
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
        // 设置key和value的序列化规则
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        // 设置hashKey和hashValue的序列化规则
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
        // 设置支持事务
        //redisTemplate.setEnableTransactionSupport(true);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
    //以下全是cache操作
    //设置10秒钟过期值的缓存管理器
    @Bean
    @Primary
    public RedisCacheManager cacheManager10Second(RedisConnectionFactory connectionFactory,RedisTemplate<K,V> redisTemplate) {
        RedisCacheConfiguration config = instanceConfig(10L,redisTemplate);
        return RedisCacheManager.builder(connectionFactory)
                .cacheDefaults(config)
                .transactionAware()
                .build();
    }
    //设置一天过期值的缓存管理器
    @Bean
    public RedisCacheManager cacheManager1Day(RedisConnectionFactory connectionFactory,RedisTemplate<K,V> redisTemplate) {
        RedisCacheConfiguration config = instanceConfig(3600 * 24L,redisTemplate);
        return RedisCacheManager.builder(connectionFactory)
                .cacheDefaults(config)
                .transactionAware()
                .build();
    }
    private RedisCacheConfiguration instanceConfig(Long ttl,RedisTemplate<K,V> redisTemplate) {
        return RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofSeconds(ttl))
                .disableCachingNullValues()
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(redisTemplate.getValueSerializer()));
    }
    //配置key值规则
    @Bean
    public KeyGenerator getKeyGenerator(){
        return new KeyGenerator() {
            @Override
            public Object generate(Object target, Method method, Object... params) {
                return target.getClass().getSimpleName() + "_"
                        + method.getName() + "_"
                        + StringUtils.arrayToDelimitedString(params, "_");
            }
        };
    }
}

@Cacheable使用

根据方法的请求参数对其结果进行缓存,下次同样的参数来执行该方法时可以直接从缓存中获取结果,而不需要再次执行该方法
@Cacheable
在service层

    //这里redis所有的key规则都是以 value:: 开头

    //keyGenerator和key只能二选一
    //key=getCache::根据keyGenerator得到完整key
    @Cacheable(value = "getCache",keyGenerator = "getKeyGenerator",cacheManager = "cacheManager10Second")
    public Object getCache2(Integer id,String name){
        //数据库插入或读取数据
        //...
        return "结果:"+id+" "+name;
    }
    key=cacheById::#id得到完整key
    @Cacheable(value = "cacheById",key="#id")
    public Object getCache(Integer id,String name){
        //数据库插入或读取数据
        //...
        Map<Object,Object> map=new HashMap<>();
        map.put(id,name);
        return map;
    }

@CachePut使用

redis更新的值存入的是方法返回值

//更新缓存必须和Cacheable的key值相同
    @CachePut(value = "cacheById",key = "#id")
    public Object updateCache(Integer id,String name){
        System.out.println("老值:"+redisTemplate.opsForValue().get("cacheById::" + id));
        //数据库更新数据
        //...
        return "结果:"+id+" "+name;
    }

@CacheEvict使用

//删除
    @CacheEvict(value = "cacheById",key = "#id")
    public void clearCache(Integer id,String name){
    	//数据库删除数据
    	//...
        System.out.println(redisTemplate.opsForValue().get("cacheById::" + id));
    }

@Caching使用

能组合多种类型操作

@Caching(
            cacheable = {
                    @Cacheable(value = "cacheById",keyGenerator = "keyGenerator")
            },
            put = {
                    @CachePut(value = "cacheById",key = "#id")
            }
    )
  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

可——叹——落叶飘零

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值