JedisClusterFactory.java
package cn.shutdown.cachecloud; import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.stereotype.Component; import redis.clients.jedis.HostAndPort; import redis.clients.jedis.JedisCluster; import java.util.HashSet; import java.util.Set; @Component public class JedisClusterFactory implements FactoryBean, InitializingBean { private String address; private JedisCluster jedisCluster; private Integer timeout; private Integer maxRedirections; private String password; private GenericObjectPoolConfig genericObjectPoolConfig; @Override public JedisCluster getObject() throws Exception { return jedisCluster; } @Override public Class extends JedisCluster> getObjectType() { return (this.jedisCluster != null ? this.jedisCluster.getClass() : JedisCluster.class); } @Override public boolean isSingleton() { return true; } private Set parseHostAndPort() throws Exception { try { String[] addressArr = address.trim().split(","); Set haps = new HashSet (); for (String addressStr : addressArr) { String[] ipAndPort = addressStr.trim().split(":"); HostAndPort hap = new HostAndPort(ipAndPort[0].trim(), Integer.parseInt(ipAndPort[1].trim())); haps.add(hap); } return haps; } catch (IllegalArgumentException ex) { throw ex; } catch (Exception ex) { throw new Exception("解析 jedis 配置文件失败", ex); } } @Override public void afterPropertiesSet() throws Exception { Set haps = this.parseHostAndPort(); jedisCluster = new JedisCluster(haps, timeout, timeout, maxRedirections, password, genericObjectPoolConfig); } public void setTimeout(int timeout) { this.timeout = timeout; } public void setMaxRedirections(int maxRedirections) { this.maxRedirections = maxRedirections; } public void setAddress(String address) { this.address = address; } public void setGenericObjectPoolConfig(GenericObjectPoolConfig genericObjectPoolConfig) { this.genericObjectPoolConfig = genericObjectPoolConfig; } public void setPassword(String password) { this.password = password; } }
spring的applicationContext.xml配置redis的连接池和工厂bean
classpath:redis.properties
redis.properties配置
#redis pool config redis.maxTotal=200 redis.maxIdle=50 redis.minIdle=10 #redis host and port config redis.address=10.4.7.212:6410,10.4.7.213:7410,10.4.7.213:6411,10.4.7.214:7411,10.4.7.214:6412,10.4.7.212:7412 redis.timeout=300000 redis.maxRedirections=6 redis.password=2651080c6814a4a9d62da69a12f962b6
测试类
public class JedisDemo3 {
public static void main(String[] args) throws Exception {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
"classpath:applicationContext2.xml");
JedisCluster jc = (JedisCluster) context.getBean("jedisCluster");
jc.set("foo", "bar");
String value = jc.get("foo");
System.out.println("value:" + value);
}
}
项目中的jedisCluster的使用
@Autowired private JedisCluster jedisCluster;
参考文档:https://www.cnblogs.com/niceplay/p/4992614.html



