SpringBoot整合Redis-Cluster集群

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; } }

 

你可能感兴趣的:(Redis,SpringBoot)