一、配置文件
pom.xml
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency><groupId>redis.clients</groupId><artifactId>jedis</artifactId><!--注意:只有2.x版本才支持,3.x版本不兼容报错NoClassDefFoundError:redis/clients/util/SafeEncoder --><version>2.9.3</version>
</dependency>
application.xml
spring:application:name: double-redis-jedisprofiles:active: devjackson:date-format: yyyy-MM-dd HH:mm:sstime-zone: GMT+8server:port: 8008sys:redis:one: host: 192.168.1.2port: 5009timeout: 6000jedis:pool:max-active: 30max-idle: 10max-wait: 6000slave:host: 192.168.1.3port: 5010database: 1two:timeout: 12000jedis:pool:max-active: 30max-idle: 10max-wait: 6000sentinel:master: redis_sentinel_masternodes:- sentinel-group001.mk.com:10003- sentinel-group002.mk.com:10003- sentinel-group003.mk.com:10003
二、配置Configuration Bean
Jedis配置基类
public abstract class AbstractJedisRedisConfig {public JedisConnectionFactory createJedisConnectionFactory(RedisProperties properties) {JedisClientConfiguration clientConfiguration = getJedisClientConfiguration(properties);RedisSentinelConfiguration sentinelConf = getSentinelConfig(properties);if (sentinelConf != null) {return new JedisConnectionFactory(sentinelConf, clientConfiguration);}RedisClusterConfiguration clusterConf = getClusterConfiguration(properties);if (clusterConf != null) {return new JedisConnectionFactory(clusterConf, clientConfiguration);}return new JedisConnectionFactory(getStandaloneConfig(properties), clientConfiguration);}private JedisClientConfiguration getJedisClientConfiguration(RedisProperties properties) {JedisClientConfiguration.JedisClientConfigurationBuilder builder = applyProperties(JedisClientConfiguration.builder(), properties);RedisProperties.Pool pool = properties.getJedis().getPool();if (pool != null) {applyPooling(pool, builder);}if (StringUtils.hasText(properties.getUrl())) {customizeConfigurationFromUrl(builder, properties);}return builder.build();}private JedisClientConfiguration.JedisClientConfigurationBuilder applyProperties(JedisClientConfiguration.JedisClientConfigurationBuilder builder,RedisProperties properties) {if (properties.isSsl()) {builder.useSsl();}if (properties.getTimeout() != null) {Duration timeout = properties.getTimeout();builder.readTimeout(timeout).connectTimeout(timeout);}return builder;}private void applyPooling(RedisProperties.Pool pool,JedisClientConfiguration.JedisClientConfigurationBuilder builder) {builder.usePooling().poolConfig(jedisPoolConfig(pool));}private JedisPoolConfig jedisPoolConfig(RedisProperties.Pool pool) {JedisPoolConfig config = new JedisPoolConfig();config.setMaxTotal(pool.getMaxActive());config.setMaxIdle(pool.getMaxIdle());config.setMinIdle(pool.getMinIdle());if (pool.getTimeBetweenEvictionRuns() != null) {config.setTimeBetweenEvictionRunsMillis(pool.getTimeBetweenEvictionRuns().toMillis());}if (pool.getMaxWait() != null) {config.setMaxWaitMillis(pool.getMaxWait().toMillis());}return config;}private void customizeConfigurationFromUrl(JedisClientConfiguration.JedisClientConfigurationBuilder builder, RedisProperties properties) {ConnectionInfo connectionInfo = parseUrl(properties.getUrl());if (connectionInfo.isUseSsl()) {builder.useSsl();}}private RedisSentinelConfiguration getSentinelConfig(RedisProperties properties) {RedisProperties.Sentinel sentinelProperties = properties.getSentinel();if (sentinelProperties != null) {RedisSentinelConfiguration config = new RedisSentinelConfiguration();config.master(sentinelProperties.getMaster());config.setSentinels(createSentinels(sentinelProperties));if (properties.getPassword() != null) {config.setPassword(RedisPassword.of(properties.getPassword()));}config.setDatabase(properties.getDatabase());return config;}return null;}private List<RedisNode> createSentinels(RedisProperties.Sentinel sentinel) {List<RedisNode> nodes = new ArrayList<>();for (String node : sentinel.getNodes()) {try {String[] parts = StringUtils.split(node, ":");Assert.state(parts.length == 2, "Must be defined as 'host:port'");nodes.add(new RedisNode(parts[0], Integer.valueOf(parts[1])));}catch (RuntimeException ex) {throw new IllegalStateException("Invalid redis sentinel " + "property '" + node + "'", ex);}}return nodes;}private RedisClusterConfiguration getClusterConfiguration(RedisProperties properties) {if (properties.getCluster() == null) {return null;}RedisProperties.Cluster clusterProperties = properties.getCluster();RedisClusterConfiguration config = new RedisClusterConfiguration(clusterProperties.getNodes());if (clusterProperties.getMaxRedirects() != null) {config.setMaxRedirects(clusterProperties.getMaxRedirects());}if (properties.getPassword() != null) {config.setPassword(RedisPassword.of(properties.getPassword()));}return config;}private RedisStandaloneConfiguration getStandaloneConfig(RedisProperties properties) {RedisStandaloneConfiguration config = new RedisStandaloneConfiguration();if (StringUtils.hasText(properties.getUrl())) {ConnectionInfo connectionInfo = parseUrl(properties.getUrl());config.setHostName(connectionInfo.getHostName());config.setPort(connectionInfo.getPort());config.setPassword(RedisPassword.of(connectionInfo.getPassword()));}else {config.setHostName(properties.getHost());config.setPort(properties.getPort());config.setPassword(RedisPassword.of(properties.getPassword()));}config.setDatabase(properties.getDatabase());return config;}private ConnectionInfo parseUrl(String url) {try {URI uri = new URI(url);boolean useSsl = (url.startsWith("rediss://"));String password = null;if (uri.getUserInfo() != null) {password = uri.getUserInfo();int index = password.indexOf(':');if (index >= 0) {password = password.substring(index + 1);}}return new ConnectionInfo(uri, useSsl, password);}catch (URISyntaxException ex) {throw new IllegalArgumentException("Malformed url '" + url + "'", ex);}}private static class ConnectionInfo {private final URI uri;private final boolean useSsl;private final String password;public ConnectionInfo(URI uri, boolean useSsl, String password) {this.uri = uri;this.useSsl = useSsl;this.password = password;}public boolean isUseSsl() {return this.useSsl;}public String getHostName() {return this.uri.getHost();}public int getPort() {return this.uri.getPort();}public String getPassword() {return this.password;}}
}
(1)第一个Redis配置
public class OneJedisRedisConfig extends AbstractJedisRedisConfig{@Beanpublic StringRedisTemplate oneStringRedisTemplate(@Autowired @Qualifier("oneRedisConnectionFactory")RedisConnectionFactory redisConnectionFactory){StringRedisTemplate template = new StringRedisTemplate();template.setConnectionFactory(redisConnectionFactory);return template;}@Beanpublic JedisConnectionFactory oneRedisConnectionFactory(@Autowired @Qualifier("oneRedisProperties") RedisProperties properties){return createJedisConnectionFactory(properties);}@Bean@ConfigurationProperties("sys.redis.one")public RedisProperties oneRedisProperties() {return new RedisProperties();}
}
(2)第二个Redis配置(主)
public class TwoJedisRedisConfig extends AbstractJedisRedisConfig{@Primary@Beanpublic StringRedisTemplate twoStringRedisTemplate(@Autowired @Qualifier("twoRedisConnectionFactory")RedisConnectionFactory redisConnectionFactory) {StringRedisTemplate template = new StringRedisTemplate();template.setConnectionFactory(redisConnectionFactory);return template;}@Primary@Beanpublic JedisConnectionFactory twoRedisConnectionFactory(@Autowired @Qualifier("twoRedisProperties") RedisProperties properties){return createJedisConnectionFactory(properties);}@Primary@Bean@ConfigurationProperties("sys.redis.two")public RedisProperties twoRedisProperties() {return new RedisProperties();}
}
(3)redis导入配置
@Configuration
@Import({OneRedisConfig.class, TwoRedisConfig.class})
public class RedisConfig {}
注意:去掉默认自动配置
@SpringBootApplication(exclude = {RedisAutoConfiguration.class})
public class Application {public static void main(String[] args) {SpringApplication.run(Application.class, args);}}