SpringBoot統合Redis-CRusterクラスタ

3108 ワード

1.依存関係の追加


   org.springframework.boot
   spring-boot-starter-data-redis

2.redis構成の追加

# Redis     
#spring.redis.host=10.100.50.23
# Redis       
#spring.redis.port=6379
# Redis       (    )
spring.redis.password=
#         (          )
spring.redis.pool.max-active=8
#            (          )
spring.redis.pool.max-wait=-1
#            
spring.redis.pool.max-idle=8
#            
spring.redis.pool.min-idle=0
#       (  )
spring.redis.timeout=0
spring.redis.commandTimeout=5000

# redis.cluster
spring.redis.cluster.nodes=10.100.50.23:6380,10.100.50.23:6381,10.100.50.23:6382,10.100.50.23:6383,10.100.50.23:6384,10.100.50.23:6385

3.カスタムredis構成

@Configuration
@ConditionalOnClass({JedisCluster.class})
public class RedisConfig {
    @Value("${spring.redis.cluster.nodes}")
    privateString clusterNodes;
    @Value("${spring.redis.timeout}")
    private inttimeout;
    @Value("${spring.redis.pool.max-idle}")
    private intmaxIdle;
    @Value("${spring.redis.pool.max-wait}")
    private longmaxWaitMillis;
    @Value("${spring.redis.commandTimeout}")
    private intcommandTimeout;
    @Bean
    publicJedisCluster getJedisCluster() {
        String[] cNodes = clusterNodes.split(",");
        Set nodes =new HashSet<>();
        //       
        for(String node : cNodes) {
            String[] hp = node.split(":");
            nodes.add(newHostAndPort(hp[0],Integer.parseInt(hp[1])));
        }
        JedisPoolConfig jedisPoolConfig =new JedisPoolConfig();
        jedisPoolConfig.setMaxIdle(maxIdle);
        jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
        //      
//      JedisCluster jedisCluster = new JedisCluster(nodes,commandTimeout);
        return newJedisCluster(nodes,commandTimeout,jedisPoolConfig);
    }
 
    /**
     *       redis       
     *redisTemplate        jdkSerializeable,        ,  key     ,     
     *    
     *
     * @paramredisConnectionFactory
     */
    @Bean
    publicRedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory)throws UnknownHostException {
        RedisTemplate redisTemplate = newRedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        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);
 
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.setKeySerializer(newStringRedisSerializer());
 
        redisTemplate.afterPropertiesSet();
 
        return redisTemplate;
    }
 
}