本文主要说明 spring boot/spring cloud 集成redis 集群,直接上代码
只需要添加三个文件即可
/*
* Copyright (c) 2018-2025, orient All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the yingcan.com developer nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Author: orient
*/
package com.minicloud.authentication.test.config;
import io.lettuce.core.ReadFrom;
import io.lettuce.core.cluster.ClusterClientOptions;
import io.lettuce.core.cluster.ClusterTopologyRefreshOptions;
import lombok.AllArgsConstructor;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisNode;
import org.springframework.data.redis.connection.RedisSentinelConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
/**
* RedisTemplate 配置
*
* @author alan.wang
*/
@Configuration
@AllArgsConstructor
@AutoConfigureBefore(RedisAutoConfiguration.class)
public class RedisTemplateConfig {
@Bean
public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate redisTemplate = new RedisTemplate<>();
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
redisTemplate.setHashValueSerializer(new JdkSerializationRedisSerializer());
redisTemplate.setConnectionFactory(redisConnectionFactory);
return redisTemplate;
}
@Bean
public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();
stringRedisTemplate.setKeySerializer(new StringRedisSerializer());
stringRedisTemplate.setConnectionFactory(redisConnectionFactory);
return stringRedisTemplate;
}
@Autowired
RedisProperties redisProperties;
@Bean
public GenericObjectPoolConfig poolConfig() {
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.setMinIdle(redisProperties.getLettuce().getPool().getMinIdle());
config.setMaxIdle(redisProperties.getLettuce().getPool().getMaxIdle());
config.setMaxTotal(redisProperties.getLettuce().getPool().getMaxActive());
config.setMaxWaitMillis(redisProperties.getLettuce().getPool().getMaxWait().toMillis());
return config;
}
@Bean
@ConditionalOnProperty(value = "spring.redis.mode",havingValue = "sentinel")
public RedisSentinelConfiguration redisSentinelConfiguration() {
RedisSentinelConfiguration redisConfig = new RedisSentinelConfiguration();
redisConfig.setMaster(redisProperties.getSentinel().getMaster());
if(redisProperties.getSentinel().getNodes()!=null) {
List sentinelNode=new ArrayList();
for(String sen : redisProperties.getSentinel().getNodes()) {
String[] arr = sen.split(":");
sentinelNode.add(new RedisNode(arr[0],Integer.parseInt(arr[1])));
}
redisConfig.setDatabase(redisProperties.getDatabase());
redisConfig.setPassword(redisProperties.getPassword());
redisConfig.setSentinelPassword(redisConfig.getPassword());
redisConfig.setSentinels(sentinelNode);
}
return redisConfig;
}
@Bean("redisConnectionFactory")
@ConditionalOnProperty(value = "spring.redis.mode",havingValue = "sentinel")
public LettuceConnectionFactory redisConnectionFactory(@Qualifier("poolConfig") GenericObjectPoolConfig config,
RedisSentinelConfiguration redisConfig) {//注意传入的对象名和类型RedisSentinelConfiguration
LettuceClientConfiguration clientConfiguration = LettucePoolingClientConfiguration.builder().poolConfig(config).build();
return new LettuceConnectionFactory(redisConfig, clientConfiguration);
}
@Bean
@ConditionalOnProperty(value = "spring.redis.mode",havingValue = "cluster")
public RedisClusterConfiguration redisClusterConfiguration() {
RedisClusterConfiguration redisClusterConfiguration = new RedisClusterConfiguration(redisProperties.getCluster().getNodes());
redisClusterConfiguration.setPassword(redisProperties.getPassword());
return redisClusterConfiguration;
}
@Bean("redisConnectionFactory")
@ConditionalOnProperty(value = "spring.redis.mode",havingValue = "cluster")
public LettuceConnectionFactory redisConnectionFactory(RedisClusterConfiguration redisClusterConfiguration) {
ClusterTopologyRefreshOptions clusterTopologyRefreshOptions = ClusterTopologyRefreshOptions.builder()
.enablePeriodicRefresh()
.enableAllAdaptiveRefreshTriggers()
.refreshPeriod(Duration.ofSeconds(5))
.build();
ClusterClientOptions clusterClientOptions = ClusterClientOptions.builder()
.topologyRefreshOptions(clusterTopologyRefreshOptions).build();
LettuceClientConfiguration lettuceClientConfiguration = LettuceClientConfiguration.builder()
.readFrom(ReadFrom.REPLICA_PREFERRED)
.clientOptions(clusterClientOptions).build();
return new LettuceConnectionFactory(redisClusterConfiguration, lettuceClientConfiguration);
}
}
请参考我的另一篇《RedisTemplateConfig sentinel(哨兵模式)/ cluster(集群模式) 常用配置 以及如何 一键配置切换》
redis:
mode: sentinel
password: 123456
sentinel:
master: local-master
nodes:
- 192.168.1.177:26379
- 192.168.1.177:26380
- 192.168.1.177:26381
lettuce:
pool:
max-active: 10
max-wait: -1
max-idle: 5
min-idle: 1
database: 3
记得顶层是spring:
org.springframework.boot
spring-boot-starter-data-redis
org.apache.commons
commons-pool2