Springboot集成redis (使用注解)

本文涉及的产品
云数据库 Tair(兼容Redis),内存型 2GB
Redis 开源版,标准版 2GB
推荐场景:
搭建游戏排行榜
简介: Springboot集成redis (使用注解),在一定程度上能够方便开发

springboot集成redis (使用注解)

注意:一般开发中小型快速应用,适合redis注解开发。但是想要合理点的设置缓存,建议还是手动配置

为什么要使用注解版?

  1. 注解版使用方便
  2. 注解版功能多样化,适合多种环境

哪种不适合缓存

  1. insert插入数据库后,返回一个int值,这个值有必要缓存???

    没必要。因为一般情况下我不会从缓存中取出int值,例如我插入了一个数据,缓存一个int值,在再插入一个数据,这种缓存一般不会被使用。

    而且插入一条数据后,就应该让该命名空间下的所有key全部移除,所以一般写的是@CacheEvict(value allEntries=true)

  • @EnableCache 开启基于注解的缓存功能
  • @Cacheable注解 :先从redis数据库中 按照当前key查找,有没有。如果redis中有,是不会走当前该方法的,如果没有再调用方法返回结果,如果结果不为null将其缓存到数据库中(一般用于find)

    • 属性:
    • value:key的一部分(前缀),主要是指明数据放在那个key范围
    • key:key的主体,#p0:指明取出第一个参数 #p1:指明取出第二个参数。。。依此类推
    • unless:结果为true,将当前的数据结果不保存到redis,#result:指明取出数据库中返回的结果
    • condition 结果如果为true,将当前数据保存到redis
    • 实例

      @Cacheable(value = RedisConfig.REDIS_DATABASE_KEY, key = "'user-'+#p0",  unless = "#result==null")
          @Override
          public User getUserByName(String name) {
              UserExample example = new UserExample();
              example.createCriteria().andNameEqualTo(name);
              List<User> users = userMapper.selectByExample(example);
              if(users.size()==0){
                  return null;
              }
              return users.get(0);
          }
      AI 代码解读
  • @CachePut: 主要用于向数据库中插入数据,向数据中插入数据的时候,会将返回的int类型,放入redis中缓存,当然是有选择性的(一般用于insert)
  • 属性:
  • value:key的一部分,命名空间
  • key:指定key的名称
  • unless:满足条件,则不将返回的结果放入redis
  • condition: 满足条件,则将返回的结果放入redis
  • 实例

    @CachePut(value = RedisConfig.REDIS_DATABASE_KEY,key = "'user-insert-'+#p0.id",unless = "#result==0")
        @Override
        public int insert(User record) {
            return userMapper.insert(record);
        }
    AI 代码解读
  • @CacheEvict:满足条件则移除当前key在redis中的数据(一般用于update/delete)

    • 属性:
    • value: 同理命名空间
    • key: key名称
    • condition:满足什么条件从缓存中移除指定的key
    • AllEntries:true/false 是否移除命名空间下的所有key
    • 实例

      @CacheEvict(value = RedisConfig.REDIS_DATABASE_KEY,key = "'user-'+#p0.id",condition = "#result==1")
          @Override
          public int updateByPrimaryKey(User record) {
              return userMapper.updateByPrimaryKey(record);
          }
      AI 代码解读
  • 问题

    我们知道如果进行查询的时候,会将数据缓存到redis中。一旦进行增删改,那么原本数据库中的数据可能会发生变化,那么增删改成功后,应该要指定的移除指定key的缓存。但是我们通过@CaheEvict移除指定key的数据,发现并不能行的通。

    为什么?

    例如:我们修改了一个product信息,那么应该移除product-id 这种key的数据,但是如果这个product数据关联,product-list等等这种key(即list中有当前修改前的数据),按理说我们应该移除这些相关联的key

    怎么做

    1. 第一种方法

      @CaheEvict(value=“nameSpace”,allEntries=true),移除这个命名空间下的所有数据

      @CaheEvict(value=“product”,allEntries=true),移除product命名空间下的所有keys

    2. 第二种

      通过redisTemplate手动移除相关联的key的数据(相对来说麻烦点)

  • 完整配置

    1. pom.xml

      <!--springboot中的redis依赖-->
      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-data-redis</artifactId>
      </dependency>
      <!-- lettuce pool 缓存连接池-->
      <dependency>
          <groupId>org.apache.commons</groupId>
          <artifactId>commons-pool2</artifactId>
      </dependency>
      AI 代码解读
    2. redisConfig

      //开启基于注解的配置
      @EnableCaching
      @Configuration
      public class RedisConfig {
      
          /**
           * redis数据库自定义key的命名空间
           */
          public static final String REDIS_DATABASE_KEY="tmall_springboot";
          public static final String REDIS_CATEGORY_KEY="category";
          public static final String REDIS_ORDER_ITEM_KEY="orderItem";
          public static final String REDIS_ORDER_KEY="order";
          public static final String REDIS_PRODUCT_KEY="product";
          public static final String REDIS_PROPERTY_KEY="property";
          public static final String REDIS_PROPERTY_VALUE_KEY="propertyValue";
          public static final String REDIS_REVIEW_KEY="review";
          public static final String REDIS_USER_KEY="user";
          public static final String REDIS_PRODUCT_IMAGE_KEY="productImage";
      
      
          /**
           * 自动配置的redisTemplate,存在序列化问题,会导致存入redis数据库中的数据,不容易看清所以需要自己配置
           */
          /**
           * 配置自定义redisTemplate
           * @return
           */
          @Bean
          RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory,RedisSerializer redisSerializer) {
      
              RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
      
              redisTemplate.setConnectionFactory(redisConnectionFactory);
      
              // 设置键(key)的序列化采用StringRedisSerializer。
              redisTemplate.setKeySerializer(new StringRedisSerializer());
              // 设置值(value)的序列化采用Jackson2JsonRedisSerializer。
              redisTemplate.setValueSerializer(redisSerializer);
              //  设置hashKey的序列化
              redisTemplate.setHashKeySerializer(new StringRedisSerializer());
              redisTemplate.setHashValueSerializer(redisSerializer);
              redisTemplate.afterPropertiesSet();
              return redisTemplate;
          }
      
          /**
           * 配置json序列化器(我们使用jackson的序列化器)
           */
          @Bean
          public RedisSerializer redisSerializer(){
      
              Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
              ObjectMapper objectMapper = new ObjectMapper();
              objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
              objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
              jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
      
              return jackson2JsonRedisSerializer;
          }
      
          /**
           * 配置redis缓存管理器,管理注解版的缓存
           */
          @Bean
          public RedisCacheManager redisCacheManager(RedisConnectionFactory redisConnectionFactory,RedisSerializer redisSerializer) {
              RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory);
              //设置Redis缓存有效期为10分钟
              RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
                      .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
                      //ttl
                      .entryTtl(Duration.ofHours(2));
              return new RedisCacheManager(redisCacheWriter, redisCacheConfiguration);
          }
      
      }
      AI 代码解读
    3. application.yml

      # 配置redis
        redis:
          host: 115.29.111.155
          port: 6379
          database: 0       #默认使用0号数据库
          timeout: 2000     #设置连接超时时间
          lettuce:
            pool:
              max-idle: 10
      AI 代码解读
    4. service层

      @Service
      public class UserServiceImpl implements UserService {
      
          @Autowired
          private UserMapper userMapper;
      
          @CacheEvict(value = RedisConfig.REDIS_USER_KEY,allEntries = true,condition = "#result==1")
          @Override
          public int deleteByPrimaryKey(Integer id) {
              return userMapper.deleteByPrimaryKey(id);
          }
      
          /**
           * @CachePut: 主要用户向数据库中插入数据,向数据中插入数据的时候,会将返回的int类型,放入redis中缓存,当然是有选择性的
           *      属性:
           *      value:key的一部分,命名空间
           *      key:指定key的名称
           *      unless:满足条件,则不将返回的结果放入redis
           *      condition: 满足条件,则将返回的结果放入redis
           */
      //    @CachePut(value = RedisConfig.REDIS_USER_KEY,key = "'insert-'+#p0.id",unless = "#result==0")
          @CacheEvict(value = RedisConfig.REDIS_USER_KEY,allEntries = true,condition = "#result==1")
          @Override
          public int insert(User record) {
              return userMapper.insert(record);
          }
      
      //    @CachePut(value = RedisConfig.REDIS_USER_KEY,key = "'insert-'+#p0.id",unless = "#result==0")
          @CacheEvict(value = RedisConfig.REDIS_USER_KEY,allEntries = true,condition = "#result==1")
          @Override
          public int insertSelective(User record) {
              return userMapper.insertSelective(record);
          }
      
          @Cacheable(value = RedisConfig.REDIS_USER_KEY,key = "'list'",unless = "#result==null")
          @Override
          public List<User> selectByExample() {
              UserExample example = new UserExample();
              example.setOrderByClause("id desc");
              List<User> users = userMapper.selectByExample(example);
              return users;
          }
      
          /**
           *   查找数据库是否存在与该名称相同的用户,如果存在true else false
           *
           *  我们这样规定,对于key而言,返回boolean的加一级 exist
           *
           */
          @Cacheable(value = RedisConfig.REDIS_USER_KEY , key = "'exist-'+#p0")
          @Override
          public boolean findUserByName(String name) {
              UserExample example = new UserExample();
              example.createCriteria().andNameEqualTo(name);
              List<User> users = userMapper.selectByExample(example);
              if(users.size()==0){
                  return false;
              }
              return true;
          }
      
          /**
           * 通过username获取用户,username是唯一的
           * redis中使用缓存缓存数据。
           *
           * @Cacheable 开启基于注解的缓存功能
           *
           * @Cacheable注解 :先从redis数据库中 按照当前key查找,有没有。如果没有再调用方法返回结果,如果结果不为null将其缓存到数据库中
           *      属性:
           *      value:key的一部分(前缀),主要是指明数据放在那个key范围
           *      key:key的主体,#p0:指明取出第一个参数  #p1:指明取出第二个参数。。。依此类推
           *      unless:结果为true,将当前的数据结果不保存到redis,#result:指明取出数据库中返回的结果
           *      condition 结果如果为true,将当前数据保存到redis
           *  此为生成的key,中文再redis中显示是这样的
           * "tmall_springboot::user-\xe5\xbc\xa0\xe4\xb8\x89"
           */
          @Cacheable(value = RedisConfig.REDIS_USER_KEY, key = "'one-name-'+#p0",  unless = "#result==null")
          @Override
          public User getUserByName(String name) {
      //        System.out.println("走该方法,数据应该缓冲");
              UserExample example = new UserExample();
              example.createCriteria().andNameEqualTo(name);
              List<User> users = userMapper.selectByExample(example);
              if(users.size()==0){
                  return null;
              }
              return users.get(0);
          }
      
          /**
           *   通过userName,password,查询是否有此用户
           */
          @Cacheable(value = RedisConfig.REDIS_USER_KEY,key = "'one-'+#p0.id",unless = "#result==null")
          @Override
          public User findOneByNameAndPassword(User user){
              UserExample example = new UserExample();
              example.createCriteria().andNameEqualTo(user.getName()).andPasswordEqualTo(user.getPassword());
              List<User> users = userMapper.selectByExample(example);
              if(users.size()==1){
                  return users.get(0);
              }
              return null;
          }
      
      
          @Cacheable(value = RedisConfig.REDIS_USER_KEY , key = "'one-'+#p0",unless = "#result==null")
          @Override
          public User selectByPrimaryKey(Integer id) {
              return userMapper.selectByPrimaryKey(id);
          }
      
          /**
           * @CacheEvict:满足条件则移除当前key在redis中的数据
           *      属性:
           *      value: 同理命名空间
           *      key: key名称
           *      condition:满足什么条件缓存到redis中
           *      allEntries: 移除value(命名空间)下,全部缓存
           */
          @CacheEvict(value = RedisConfig.REDIS_USER_KEY,allEntries = true,condition = "#result==1")
          @Override
          public int updateByPrimaryKeySelective(User record) {
              return userMapper.updateByPrimaryKeySelective(record);
          }
      
          @CacheEvict(value = RedisConfig.REDIS_USER_KEY,allEntries = true,condition = "#result==1")
          @Override
          public int updateByPrimaryKey(User record) {
              return userMapper.updateByPrimaryKey(record);
          }
      }
      AI 代码解读
相关实践学习
基于Redis实现在线游戏积分排行榜
本场景将介绍如何基于Redis数据库实现在线游戏中的游戏玩家积分排行榜功能。
云数据库 Redis 版使用教程
云数据库Redis版是兼容Redis协议标准的、提供持久化的内存数据库服务,基于高可靠双机热备架构及可无缝扩展的集群架构,满足高读写性能场景及容量需弹性变配的业务需求。 产品详情:https://www.aliyun.com/product/kvstore &nbsp; &nbsp; ------------------------------------------------------------------------- 阿里云数据库体验:数据库上云实战 开发者云会免费提供一台带自建MySQL的源数据库&nbsp;ECS 实例和一台目标数据库&nbsp;RDS实例。跟着指引,您可以一步步实现将ECS自建数据库迁移到目标数据库RDS。 点击下方链接,领取免费ECS&amp;RDS资源,30分钟完成数据库上云实战!https://developer.aliyun.com/adc/scenario/51eefbd1894e42f6bb9acacadd3f9121?spm=a2c6h.13788135.J_3257954370.9.4ba85f24utseFl
目录
打赏
0
0
0
0
5
分享
相关文章
微服务——SpringBoot使用归纳——Spring Boot 中集成Redis——Redis 介绍
本文介绍在 Spring Boot 中集成 Redis 的方法。Redis 是一种支持多种数据结构的非关系型数据库(NoSQL),具备高并发、高性能和灵活扩展的特点,适用于缓存、实时数据分析等场景。其数据以键值对形式存储,支持字符串、哈希、列表、集合等类型。通过将 Redis 与 Mysql 集群结合使用,可实现数据同步,提升系统稳定性。例如,在网站架构中优先从 Redis 获取数据,故障时回退至 Mysql,确保服务不中断。
100 0
微服务——SpringBoot使用归纳——Spring Boot 中集成Redis——Redis 介绍
|
1月前
|
基于SpringBoot的Redis开发实战教程
Redis在Spring Boot中的应用非常广泛,其高性能和灵活性使其成为构建高效分布式系统的理想选择。通过深入理解本文的内容,您可以更好地利用Redis的特性,为应用程序提供高效的缓存和消息处理能力。
158 79
|
2月前
|
Springboot使用Redis实现分布式锁
通过这些步骤和示例,您可以系统地了解如何在Spring Boot中使用Redis实现分布式锁,并在实际项目中应用。希望这些内容对您的学习和工作有所帮助。
218 83
SpringBoot整合Redis、ApacheSolr和SpringSession
本文介绍了如何使用SpringBoot整合Redis、ApacheSolr和SpringSession。SpringBoot以其便捷的配置方式受到开发者青睐,通过引入对应的starter依赖,可轻松实现功能整合。对于Redis,可通过配置RedisSentinel实现高可用;SpringSession则提供集群Session管理,支持多种存储方式如Redis;整合ApacheSolr时,借助Zookeeper搭建SolrCloud提高可用性。文中详细说明了各组件的配置步骤与代码示例,方便开发者快速上手。
49 11
|
28天前
|
微服务——SpringBoot使用归纳——Spring Boot 中集成Redis——Spring Boot 集成 Redis
本文介绍了在Spring Boot中集成Redis的方法,包括依赖导入、Redis配置及常用API的使用。通过导入`spring-boot-starter-data-redis`依赖和配置`application.yml`文件,可轻松实现Redis集成。文中详细讲解了StringRedisTemplate的使用,适用于字符串操作,并结合FastJSON将实体类转换为JSON存储。还展示了Redis的string、hash和list类型的操作示例。最后总结了Redis在缓存和高并发场景中的应用价值,并提供课程源代码下载链接。
70 0
|
28天前
|
微服务——SpringBoot使用归纳——Spring Boot 中集成Redis——Redis 安装
本教程介绍在 VMware 虚拟机(CentOS 7)或阿里云服务器中安装 Redis 的过程,包括安装 gcc 编译环境、下载 Redis(官网或 wget)、解压安装、修改配置文件(如 bind、daemonize、requirepass 等设置)、启动 Redis 服务及测试客户端连接。通过 set 和 get 命令验证安装是否成功。适用于初学者快速上手 Redis 部署。
32 0
微服务——SpringBoot使用归纳——Spring Boot集成MyBatis——基于注解的整合
本文介绍了Spring Boot集成MyBatis的两种方式:基于XML和注解的形式。重点讲解了注解方式,包括@Select、@Insert、@Update、@Delete等常用注解的使用方法,以及多参数时@Param注解的应用。同时,针对字段映射不一致的问题,提供了@Results和@ResultMap的解决方案。文章还提到实际项目中常结合XML与注解的优点,灵活使用两者以提高开发效率,并附带课程源码供下载学习。
37 0
|
3月前
基于springboot+thymeleaf+Redis仿知乎网站问答项目源码
基于springboot+thymeleaf+Redis仿知乎网站问答项目源码
184 36
注解的方式实现redis分布式锁
创建redisLock注解: import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.
1228 0
|
28天前
|
Redis--缓存击穿、缓存穿透、缓存雪崩
缓存击穿、缓存穿透和缓存雪崩是Redis使用过程中可能遇到的常见问题。理解这些问题的成因并采取相应的解决措施,可以有效提升系统的稳定性和性能。在实际应用中,应根据具体场景,选择合适的解决方案,并持续监控和优化缓存策略,以应对不断变化的业务需求。
95 29

热门文章

最新文章

AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等