美文网首页
SpringBoot 集成 Redis

SpringBoot 集成 Redis

作者: Tinyspot | 来源:发表于2022-11-21 21:53 被阅读0次

    1. 集成 Redis

    1.1 导入依赖包

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    

    补充:
    进入 spring-boot-starter-data-redis.pom 文件查看,默认使用的是lettuce

    <dependency>
      <groupId>org.springframework.data</groupId>
      <artifactId>spring-data-redis</artifactId>
    </dependency>
    <dependency>
      <groupId>io.lettuce</groupId>
      <artifactId>lettuce-core</artifactId>
    </dependency>
    

    若要使用 jedis,需要排除lettuce

    <dependency>
        <groupId>redis.clients</groupId>
        <artifactId>jedis</artifactId>
        <version>4.2.3</version>
    </dependency>
    

    1.2 配置文件

    spring:
      datasource:
        driver-class-name: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://mysql.sqlpub.com:3306/spotlive
        username: xxx
        password: xxx
      redis:
        database: 0
        host: 127.0.0.1
        port: 6379
        password: admin
        jedis:
          pool:
            max-active: 8
            max-idle: 8
            min-idle: 6
    

    1.3 示例

    @RestController
    @RequestMapping("/redis")
    public class RedisController {
    
        private final RedisTemplate redisTemplate;
    
        public RedisController(RedisTemplate redisTemplate) {
            this.redisTemplate = redisTemplate;
        }
    
        @GetMapping("/set")
        public String save(String key, String value){
            redisTemplate.opsForValue().set(key, value);
            return "success";
        }
    
        @RequestMapping("/get")
        public String getValue(String key) {
            return redisTemplate.opsForValue().get(key).toString();
        }
    
        @RequestMapping("/all")
        public String getAll() {
            // return JSON.toJSONString(redisTemplate.keys("*"));
            return JSON.toJSONString(redisTemplate.keys("*o*"));
        }
    }
    

    2. 序列化问题

    查看key值,出现无意义的乱码前缀

    127.0.0.1:6379> keys *
    1) "\xac\xed\x00\x05t\x00\x04name"
    

    原因是 Redis 默认使用的是JdkSerializationRedisSerializer

    public class RedisTemplate<K, V> extends RedisAccessor implements RedisOperations<K, V>, BeanClassLoaderAware {
        public void afterPropertiesSet() {
            super.afterPropertiesSet();
            boolean defaultUsed = false;
            if (this.defaultSerializer == null) {
                this.defaultSerializer = new JdkSerializationRedisSerializer(this.classLoader != null ? this.classLoader : this.getClass().getClassLoader());
            }
            // ...
        }
    }
    

    方式一:使用 StringRedisTemplate

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    

    方式二:设置RedisTemplate序列化

    @Configuration
    public class RedisConfig {
    
        @Bean(name = "redisTemplate")
        public RedisTemplate<String, Object> getRedisTemplate(RedisConnectionFactory factory) {
            RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
            redisTemplate.setConnectionFactory(factory);
    
            StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
            redisTemplate.setKeySerializer(stringRedisSerializer);
            redisTemplate.setValueSerializer(stringRedisSerializer);
    
            redisTemplate.afterPropertiesSet();
            return redisTemplate;
        }
    }
    

    使用:

    @Resource
    private RedisTemplate redisTemplate;
    

    2.2 其他

    @Configuration
    public class RedisConfig {
    
        @Bean(name = "redisTemplate")
        public RedisTemplate<String, Object> getRedisTemplate(RedisConnectionFactory factory) {
            RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
            redisTemplate.setConnectionFactory(factory);
    
            StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
            redisTemplate.setKeySerializer(stringRedisSerializer);
            redisTemplate.setValueSerializer(jacksonSerializer());
            redisTemplate.setHashKeySerializer(stringRedisSerializer);
            redisTemplate.setHashValueSerializer(jacksonSerializer());
    
            redisTemplate.afterPropertiesSet();
            return redisTemplate;
        }
    
        private Jackson2JsonRedisSerializer jacksonSerializer() {
            Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
            objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance,
                    ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
            jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
            return jackson2JsonRedisSerializer;
        }
    }
    

    相关文章

      网友评论

          本文标题:SpringBoot 集成 Redis

          本文链接:https://www.haomeiwen.com/subject/nennxdtx.html