Spring boot集成Spring cache

Spring Cache集成redis的运行原理:

Spring缓存抽象模块通过CacheManager来创建、管理实际缓存组件,当SpringBoot应用程序引入spring-boot-starter-data-redi依赖后吗,容器中将注册的是CacheManager实例RedisCacheManager对象,RedisCacheManager来负责创建RedisCache作为缓存管理组件,由RedisCache操作redis服务器实现缓存数据操作。实际测试发现默认注入的RedisCacheManager操作缓存用的是RedisTemplate<Object, Object>,因此我们需要自定义cacheManager,替换掉默认的序列化器。
pom依赖

<!-- 引入redis启动依赖 -->
       <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-data-redis</artifactId>
       </dependency>
<!-- 引入jedis依赖 -->
       <dependency>
           <groupId>redis.clients</groupId>
           <artifactId>jedis</artifactId>
       </dependency>
代码层:service层

这里的缓存利用的是aop,所以我们需要在设置缓存的方法上返回对应的实体类数据,这样才能进行设置缓存

@CacheConfig(cacheNames = "userService")
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService {
 /**
    * @Description: 新增设置缓存,并且返回值有值的情况下才进行设置
    * condition = "#result!=nul  当返回结果有值的情况下,进行设置缓存
    */
    @Override
//  @CachePut(key = "'user:' + #user.id")
//  @CachePut(key = "#root.methodName + '[' + #user.id + ']'" , condition = "#result!=null")
    @CachePut(key = "'user:' + '[' + #user.id + ']'" , condition = "#result!=null")
    public User insertData(User user) {
        super.save(user);
        return user;
    }
 /**
  * @Description: Cacheable 注解,首次如果缓存中没有则会走数据库查询,查到数据之后会按照设置的key进行缓存数据
  */
//  @Cacheable(key = "'user:' + #id")
    @Cacheable(key = "'user:' + '[' + #id + ']'" )
    public User getById(Long id){
        System.err.println("没走缓存=============");
        return super.getById(id);
    }
    /**
     * CachePut 更新的时候更新数据库并且更新缓存数据,key值需要配置一致
     */
    @CachePut(key = "'user:' + '[' + #user.id + ']'")
    public User updateById1(User user){
        System.out.println("走修改");
        super.updateById(user);
        return user;
    }
    /**
     * 删除的时候直接根据key值删除
     */
    // @CacheEvict(allEntries=true,beforeInvocation=true):代表清除所有缓存
    @CacheEvict(key = "'user:' + '[' +#id+ ']'")
    public Boolean delById(Long id){
        System.out.println("走删除");
        boolean b = super.removeById(id);
        System.out.println(b);
        return b;
    }

redis缓存数据结果

key的命名规则:

@CacheConfig的cacheNames: + @Cacheable/@CachePut的key
如果设置完成之后发现缓存的key包含\xac\xed\x00\x05t\x00\tb这么多不友好的字符,出门左转:

https://blog.csdn.net/wwrzyy/article/details/85089463
Spring data 官方文档:https://docs.spring.io/spring-data/redis/docs/2.1.0.M1/api/

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值