Springboot缓存与redis整合

Springboot缓存
  1. Spring缓存抽象
    1. 重要概念以及缓存注解
      1. Cache:缓存接口,定义缓存操作,实现又:RedisCache,EhCacheCache,ConcurrentMapCache等
      2. CacheManager:缓存管理器,管理各种缓存组件
      3. @Cacheable:修饰方法,能够根据方法的请求参数和返回结果进行缓存
      4. @CacheEvict:修饰方法,清空缓存,例如从数据库删除某个用户,那就需要把相应的缓存也删除掉
      5. @CachePut:修饰方法,调用函数,更新缓存
        1. @Cacheable一旦缓存命中,就不再调用修饰的函数了
        2. @CachePut一定会调用函数,并把值放到缓存,常用于更新操作,先调用函数,在更新缓存
      6. @EnableCaching:开启基于注解的缓存模式
      7. keyGenerator:缓存数据时key的生成策略
      8. serialize:缓存数据时value序列化策略
    2. 搭建环境
      1. 引入包
        1. < dependency>
        2. < groupId > org.springframework.boot </ groupId >
        3. < artifactId > spring-boot-starter-cache </ artifactId >
        4. </ dependency >
      2. 使用缓存
        @Cacheable
        public  String getUser( int  id){
        System. out .println( " 缓存未命中 " );
        return  "zhangsan" ;
        }
        1. 开启基于注解的缓存
          1.  
             
        2. 使用缓存
    3. @Cacheable
      @Caching(
      cacheable={ @Cacheable (), @Cacheable ()},
      put={},
      evict = {}
      )
      1. 属性
        1. cacheNames/value :数组,缓存名字,因为缓存管理器下有许多缓存,所以这个指定从哪个缓存中查找数据,或者将数据存入哪个缓存中,可以将一份数据存到多个缓存
          1. @Cacheable(cacheNames="emp")
        2. key:存缓存或者查找缓存value时用的键,支持spel表达式。默认key为参数的值
          1. @Cacheable的key不能用#result
        3. keyGenerator:key的生成器,可以指定key生成器的组件id,key和 keyGenerator两个属性二选一
          @Configuration
          public class  CacheAutoConfiguration{
          @Bean ( "myKeyGenerator" )
          public  KeyGenerator keyGenerator(){
          return new  KeyGenerator() {
          @Override
          public  Object generate(Object target, Method method, Object... params) {
          return  "hahaha" ;
          }
          }
          }
          }
          1. 自定义 keyGenerator
          2. 使用自定义的 keyGenerator
            1. @Cacheable (cacheNames =  "emp" , keyGenerator =  "myKeyGenerator" )
        4. cacheManager:指定从哪个缓存管理器中拿到缓存,
        5. cacheResolver:指定寻找  cacheManager的策略, cacheResolver与 cacheManager二选一
        6. condition:可以使用spel表达式,满足条件才缓存
        7. unless:满足unless条件,则不缓存,可以获取到结果进行判断
          1. @Cacheable(unless="#result == null")
        8. sync:是否使用异步模式,默认false.意思是。在put数据时,是异步还是同步
      2. 原理
        1. 自动配置类: CacheAutoConfiguration
        2. Import选择器: CacheConfigurationImportSelector
          1. org.springframework.boot.autoconfigure.cache.GenericCacheConfiguration
          2. org.springframework.boot.autoconfigure.cache.JCacheCacheConfiguration
          3. org.springframework.boot.autoconfigure.cache.EhCacheCacheConfiguration
          4. org.springframework.boot.autoconfigure.cache.HazelcastCacheConfiguration
          5. org.springframework.boot.autoconfigure.cache.InfinispanCacheConfiguration
          6. org.springframework.boot.autoconfigure.cache.CouchbaseCacheConfiguration
          7. org.springframework.boot.autoconfigure.cache.RedisCacheConfiguration
          8. org.springframework.boot.autoconfigure.cache.CaffeineCacheConfiguration
          9. org.springframework.boot.autoconfigure.cache.SimpleCacheConfiguration
          10. org.springframework.boot.autoconfigure.cache.NoOpCacheConfiguration
        3. 哪个配置生效呢?
          1. 每个CacheConfiguration上面都用注解标识了生效条件
          2. SimpleCacheConfiguration这个有可能生效
        4. SimpleCacheConfiguration给容器中注入了一个CacheManager( ConcurrentMapCacheManager)的bean
          1. ConcurrentMapCacheManager维护了一个Map<String, ConcurrentMapCache>,String为缓存的名字
        5. ConcurrentMapCacheManager可以获取和创建 ConcurrentMapCache组件,并将数据放到 ConcurrentMapCache中
          1. ConcurrentMapCache就是一个类,属性有name和 ConcurrentMap
        6. 整个流程
      3. @CachePut
        1. 先调用函数在更新缓存
        2. 注意点
          1. @Cacheable添加缓存
            1. @Cacheable(cacheNames =  "emp", keyGenerator =  "myKeyGenerator")
            2. public  String getUser( int  id){
          2. @ CachePut添加缓存
            1. @CachePut (cacheNames =  "emp" )
            2. public  Employee update(Employee emp){
          3. 这两个缓存的key的生成可能不一杨,可能会导致他们更新的缓存原本应该是同一个,但是却由于生成key不一样,导致缓存更新错误
      4. @CacheEvict
        1. key:指定要清除的key
        2. allEntries=true:清除缓存中的所有数据,默认false
        3. beforeInvocation=true:实在方法执行之前清除缓存,还是在方法执行之后清除缓存,默认为false,
          1. 如果在方法执行之后清除缓存,一旦方法出现异常,那么缓存不会被清除
      5. @Caching可以使用组合注解
      6. @CacheConfig修饰类,可以将 Cacheable, CachePut, CacheEvict的公共属性提取出来
  2. 整合redis使用缓存
     
    1. 引入依赖
      1. <!-- springboot整合redis的starter- ->
      2. < dependency>
      3. < groupId > org.springframework.boot </ groupId >
      4. < artifactId > spring-boot-starter-data-redis </ artifactId >
      5. </ dependency >
      6. <!-- redis如果要使用连接池技术,需要依赖这个包- ->
      7. < dependency >
      8. < groupId > org.apache.commons </ groupId >
      9. < artifactId > commons-pool2 </ artifactId >
      10. </ dependency >
      11. <!-- 由于我们需要更改对象序列化为json存到redis中,需要这个包 -->
      12. < dependency >
      13. < groupId > com.fasterxml.jackson.core </ groupId >
      14. < artifactId > jackson-core </ artifactId >
      15. < version > 2.9.8 </ version >
      16. </ dependency >
      17. <!--  从redis读取数据,反序列化为对象时,绑定数据需要这个包  -->
      18. < dependency >
      19. < groupId > com.fasterxml.jackson.core </ groupId >
      20. < artifactId > jackson-databind </ artifactId >
      21. < version > 2.9.8 </ version >
      22. </ dependency >
    2. 配置redis连接池
      1. spring:
        1. redis :
          1. host : 127.0.0.1
          2. port :  6379
          3. database :  0
          4. lettuce :
            1. pool :
              1. #  连接池最大连接数 默认 8  ,负数表示没有限制
              2. max-active :  20
              3. #  连接池中的最大空闲连接 默认 8
              4. max-idle :  10
              5. #  连接池最大阻塞等待时间(使用负值表示没有限制) 默认 -1
              6. max-wait : 1000
          5. timeout : 10000
    3. 修改cacheManager的默认配置
    4. public CacheManager cacheManager(LettuceConnectionFactory redisConnectionFactory) {
      // 初始化一个 RedisCacheWriter
      RedisCacheWriter redisCacheWriter = RedisCacheWriter. nonLockingRedisCacheWriter (redisConnectionFactory);
      // 设置 CacheManager 的值序列化方式为 json 序列化
      Jackson2JsonRedisSerializer<Person> jackson2JsonRedisSerializer =  new  Jackson2JsonRedisSerializer<>(Person. class );
      RedisSerializationContext.SerializationPair<Person> pair = RedisSerializationContext.SerializationPair
      . fromSerializer (jackson2JsonRedisSerializer);
      RedisCacheConfiguration defaultCacheConfig= RedisCacheConfiguration. defaultCacheConfig ()
      .serializeValuesWith(pair)
      .entryTtl(Duration. ofSeconds ( 30 )) // 设置默认超过期时间是 30
      .disableCachingNullValues();
       
      // 初始化 RedisCacheManager
      return new  RedisCacheManager(redisCacheWriter, defaultCacheConfig);
      }
    5. 使用注解即可
      1. 开启缓存@EnableCaching
      2. 在相应方法上添加注解
        1. @Cacheable(cacheNames =  "statuschecker")
        2. public  Person request( int  id){
          1. System. out .println( "Cache 未命中 " );
          2. return new  Person( "www" , 24 );
        3. }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值