SpringCache实现缓存

Posted 可——叹——落叶飘零

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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")
            
    )

以上是关于SpringCache实现缓存的主要内容,如果未能解决你的问题,请参考以下文章

SpringCache - 请求级别缓存的简易实现

SpringCache通用缓存学习

SpringCache通用缓存学习

SpringCache实现缓存

SpringCache实现缓存

SpringCache实现缓存