springboot整合redis集群

springboot整合redis集群

yls
2019-9-21


简介

在springboot使用搭建好的redis集群

添加redis和连接池依赖

   <!--redis连接池 start-->
       <dependency>
           <groupId>org.apache.commons</groupId>
           <artifactId>commons-pool2</artifactId>
       </dependency>
       <!--redis连接池 end-->

       <!--redis start-->
       <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-data-redis</artifactId>
           <version>2.2.6.RELEASE</version>
       </dependency>
       <!--redis end-->

在配置文件中配置连接池和sentinel

ip: 39.97.234.52
spring:
  redis:
    lettuce:
      pool:
        max-active: 10
        max-idle: 8
        max-wait: -1ms
        min-idle: 0
    sentinel:
      master: mymaster
      nodes: ${ip}:26379,${ip}:26380,${ip}:26381
    password: test@dbuser2018

添加redis配置类,修改springboot默认的redis序列化方式

@Configuration
public class RedisConfig {
    /**
     * 设置手动存的序列化
     * 把任何数据保存到redis时,都需要进行序列化,默认使用JdkSerializationRedisSerializer进行序列化。
     * 默认的序列化会给所有的key,value的原始字符前,都加了一串字符(例如:\xAC\xED\x00\),不具备可读性
     * 所以需要配置jackson序列化方式
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper objectMapper = new ObjectMapper();
        // 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        // 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常
        objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        //key采用String的序列化方式
        template.setKeySerializer(stringRedisSerializer);
        //value采用jackson序列化方式
        template.setValueSerializer(jackson2JsonRedisSerializer);
        //hash的key采用String的序列化方式
        template.setHashKeySerializer(stringRedisSerializer);
        //hash的value采用String的序列化方式
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }

    /**
     * 设置cache的序列化,如果没有使用spring cache缓存,就不需要配置这个
     *
     * @param factory
     * @return
     */
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory) {
        //新建一个Jackson2JsonRedis的redis存储的序列化方式
        GenericJackson2JsonRedisSerializer genericJackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
        //解决查询缓存转换异常的问题
        // 配置序列化(解决乱码的问题)
        //entryTtl设置过期时间
        //serializeValuesWith设置redis存储的序列化方式
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofSeconds(10))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(genericJackson2JsonRedisSerializer))
                .disableCachingNullValues();
        //定义要返回的redis缓存管理对象
        RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
                .cacheDefaults(config)
                .build();
        return cacheManager;
    }
}

创建redis服务

    @Service
    public class RedisServiceImpl implements RedisService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean put(String key, Object value, long seconds) throws JsonProcessingException {
        redisTemplate.opsForValue().set(key, value, seconds, TimeUnit.SECONDS);
        return true;
    }

    @Override
    public <T> T get(String key, Class<T> clazz) throws IOException {
        Object o = redisTemplate.opsForValue().get(key);
        if (o != null) {
            String json = String.valueOf(o);
            T t = JsonUtil.stringToObject(json, clazz);
            return t;
        }
        return null;
    }
    }

创建redisController测试redis服务

    @RestController
    public class RedisController {

        @Autowired
        private RedisService redisService;

        @PostMapping(value = "put")
        public String put(String key,String value,long seconds){

            redisService.put(key,value,seconds);
            return "ok";
        }

        @GetMapping(value = "get")
        public Object get(String key){

            Object o=redisService.get(key);
            if(o!=null){
                return String.valueOf(o);
            }
            return "not_ok";
        }
    }

如果缓存的类中有 LocalDateTime 系列属性,需要在字段上做如下配置

    @JsonDeserialize(using = LocalDateTimeDeserializer.class)
    @JsonSerialize(using = LocalDateTimeSerializer.class)
    private LocalDateTime updateTime;
posted @ 2019-09-21 01:16  她的开呀  阅读(14582)  评论(0编辑  收藏  举报