开发者

SpringBoot整合Redis的实现示例

开发者 https://www.devze.com 2023-01-25 10:18 出处:网络 作者: llp1110
目录1.需求说明2.整合实现2.1.创建Springboot工程2.2.Redis配置3.编写测试类4.注意事项和细节1.需求说明
目录
  • 1.需求说明
  • 2.整合实现
    • 2.1.创建Springboot工程
    • 2.2.Redis配置
  • 3.编写测试类
    • 4.注意事项和细节

      1.需求说明

      • 在 springboot 中 , 整合 redis
      • 可以通过 RedisTemplate 完成对 redis 的操作, 包括设置数据/获取数据
      • 比如添加和读取数据

      2.整合实现

      2.1.创建Springboot工程

      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-web</artifactId>
      </dependency>
      
      <!-- redis -->
      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-data-redis</artifactId>
      </dependency>
      <!-- spring2.X 集成 redis 所需 common-pool-->
      <dependency>
          <groupId>org.apache.commons</groupId>
          <artifactId>commons-pool2</artifactId>
          <!--不要带版本号,防止冲突-->
      </dependency>
      
      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-test</artifactId>
          <scope>test</scope>
      </dependency>
      <dependency>
          <groupId>com.fasterXML.jackson.core</groupId>
          <artifactId>jackson-databind</artifactId>
          <version>2.13.2.2</version>
      </dependency>
      开发者_Go培训

      2.2.redis配置

      配置连接信息

      spring:
        redis:
          host: 192.168.79.202
          port: 6379
          #Redis 数据库索引(默认为 0)
          database: 0
          #连接超时时间(毫秒)
          timeout: 1800000
          lettuce:
            pool:
              #连接池最大连接数(使用负值表示没有限制)
              max-active: 20
              #最大阻塞等待时间(负数表示没限制)
              max-wait: -1
              #连接池中的最大空闲连接
              min-idle: 0
              #密码
          password: foobared
      

      redis 配置类

      如果不配置, springboot 会使用默认配置, 这个默认配置, 会出现一些问题, 比如:

      redisTemplate 的 key 序列化等, 问题所以通常我们需要配置

      @EnableCaching
      @Configuration
      public class RedisConfig extends CachingConfigurerSupport {
      
          @Bean
          public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
              RedisTemplate<String, Object> template =
                      new RedisTemplate<>();
              //这里可以验证..
              //System.out.println("template=>" + template);
              RedisSerializer<String> stringRedisSerializer =
                      new StringRedisSerializerjs();
              Jackson2jsonRedisSerializer jackson2JsonRedisSerializer =
                      new Jackson2JsonRedisSerializer(Object.class);
              ObjectMapper om = new ObjectMapper();
              om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
              om.activateDefaultTyping(
                      LaissezFaireSubTypeValidator.instance,
                      ObjectMapper.DefaultTyping.NON_FINAL,
                      JsonTypeInfo.As.WRAPPER_ARRAY);
              jackson2JsonRedisSerializer.setObjectMapper(om);
              template.setConnectionFactory(factory);
              //key序列化方式
              template.setKeySerializer(stringRedisSerializer);
              //value序列化
              template.setValueSerializer(jackson2JsonRedisSerializer);
              //value hashmap序列化
              template.setHashValueSerializer(jackson2JsonRedisSerializer);
              return template;
          }
      
          @Bean
          public CacheManager cacheManager(RedisConnectionFactory factory) {
              RedisSerializer<String> stringRedisSerializer =
                      new StringRedisSerializer();
              Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
              //解决查询缓存转换异常的问题
              ObjectMapper om = new ObjectMapper();
              om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
              om.activateDefaultTyping(
                      LaissezFaireSubTypeValidator.instance,
                      ObjectMapper.DefaultTyping.NON_FINAL,
                      JsonTypeInfo.As.WRAPPER_ARRAY);
              jackson2JsonRedisSerializer.setObjectMapper(om);
              // 配置序列化(解决乱码的问题),过期时间600秒
              RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                      .entryTtl(Duration.ofSeconds(600))
                      .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(stringRedisSerializer))
                      .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
                      .disableCachingNullValues();
              RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
                      .cacheDefaults(config)
                      .build();
              return cacheManager;
          }
      }
      

      3.编写测试类

      @RestController
      @RequestMapping("/redisTest")
      public class RedisTestController {
      
          @Resource
          private RedisTemplate redisTemplate;
      
          //编写一个测试方法,演示设置数据和获取数据
          @GetMapping("/t1")
          public String t1(){
              //设置值到redis
              redisTemplate.opsForValue().set("book","西游记");
              //从redis获取值
              String book = (String)redisTemplate.opsForValue().get("book");
              return book;
          }
      
      }
      

      测试结果

      SpringBoot整合Redis的实现示例

      SpringBoot整合Redis的实现示例

      //编写方法,演示如何操作list,hash,set,zset
      //opsForList、opsForHash、opsForSet、opsForZSet
      @GetMapping("/t2")
      public String t2(){
          rjsedisTemplate.opsForList().leftPushAll("books","西游记","Java");
          List books = redisTemplate.opsForList().range("books", 0, -1);
          StringBuilder builder = new StringBuilder();
          for (Object book : books) {
              builder.append(book.toString()).append(" ");
              System.out.println("书名:"+book.toString())编程客栈;
          }
          return builder.toString();
      }
      

      输出结果

      书名:java

      书名:西游记

      4.注意事项和细节

      1、如果没有提供 RedisConfig 配置类 , springboot 会使用默认配置, 也可以使用

      2、如果没有提供 RedisConfig 配置类 , springboot 会使用默认配置, 但是会存在问题,比如 redisTemplate 模糊查找 key 数据为空

      //编写一个方法获取所有的key
      @GetMapping("/t3")
      public String t3(){
          Set keys = redisTemplate.keys("*");
          System.out.println(keys.size());
          System.out.println(keys);
          return "ok";
      }
      //输出结果
      0
      []

      3、Unrecognized token ‘beijing’: was expecting (‘true’, ‘false’ or ‘null’)看报错,是 jason 转换异常,实际上是因为 redisTemplate 在做数据存储的时候会把存储的内容序列化,所以,redisTemplate 读取的时候也会反序列化,而在 redis 客户端set 的时候并不会做序列化,因此 set 的进去的值在用 redisTemplate 读的时候就会报类型转换异常了

      SpringBoot整合Redis的实现示例

      //编写方法获取客户端设python置的key
      //问题描述:在客户端设置了key,通过redisTemplate获取会报错
      @GetMapping("/t4")
      public String t4(){
          String name = (String)redisTemplate.opsForValue().get("name");
          System.out.p编程客栈rintln("name = "+name);
          return name;
      }
      

      SpringBoot整合Redis的实现示例

      4、解决方案 : 最简单的就是用程序重新 set 一遍即可

      到此这篇关于SpringBoot整合Redis的实现示例的文章就介绍到这了,更多相关SpringBoot整合Redis内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

      0

      精彩评论

      暂无评论...
      验证码 换一张
      取 消

      关注公众号