springboot项目中多个Redis数据源配置
多个Redis数据源配置
·
多个不同数据源的Redis配置类
需要引入jia
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
详细代码如下:
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import java.util.HashSet;
import java.util.Set;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
/**
* @author **********
* Created on 2021/12/8.
*/
@Configuration
@EnableCaching
public class JedisClusterConfig {
//nacos配置项取值
@Value("${spring.redis.cluster.nodes}")
String cluster1;
@Value("${spring.redis1.cluster.nodes}")
String cluster2;
@Value("${spring.redis.password}")
String password1;
@Value("${spring.redis1.password}")
String password2;
@Value("${spring.redis.lettuce.pool.min-idle}")
String minIdle;
@Value("${spring.redis.lettuce.pool.max-idle}")
String maxIdle;
@Value("${spring.redis.lettuce.pool.max-active}")
String active;
@Value("${spring.redis.lettuce.pool.max-wait}")
String wait;
/**
* 注意:
* 这里返回的JedisCluster是单例的,并且可以直接注入到其他类中去使用
* @return
*/
@Bean(name = "name1")
@Primary
public JedisCluster getJedisCluster1() {
String[] serverArray =cluster1.split(",");//获取服务器数组
Set<HostAndPort> nodes = getHostAndPorts(serverArray);
GenericObjectPoolConfig config = getGenericObjectPoolConfig();
return new JedisCluster(nodes,10000,1000,1,password1,config);
}
/**
* 注意:
* 这里返回的JedisCluster是单例的,并且可以直接注入到其他类中去使用
* @return
*/
@Bean(name = "name2")
public JedisCluster getJedisCluster2() {
String[] serverArray =cluster2.split(",");//获取服务器数组
Set<HostAndPort> nodes = getHostAndPorts(serverArray);
GenericObjectPoolConfig config = getGenericObjectPoolConfig();
return new JedisCluster(nodes,10000,1000,1,password2,config);
}
private Set<HostAndPort> getHostAndPorts(String[] serverArray) {
Set<HostAndPort> nodes = new HashSet<>();
for (String ipPort : serverArray) {
String[] ipPortPair = ipPort.split(":");
nodes.add(new HostAndPort(ipPortPair[0].trim(), Integer.parseInt(ipPortPair[1].trim())));
}
return nodes;
}
private GenericObjectPoolConfig getGenericObjectPoolConfig() {
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.setMaxIdle(Integer.parseInt(maxIdle));
config.setMaxTotal(Integer.parseInt(active));
config.setMinIdle(Integer.parseInt(minIdle));
config.setMaxWaitMillis(Long.parseLong(wait));
return config;
}
}
在其他类中注入哪个即用哪个
@Resource(name = "name1")
private JedisCluster jedisCluster;
更多推荐
所有评论(0)