spring jedis 配置


1、自定义一个工厂类,实现FactoryBean 交由spring管理
public class JedisClusterFactory implements FactoryBean<JedisCluster> {

private String hostAndPort;

private JedisCluster jedisCluster;

private Integer timeout;

private Integer maxRedirections;

private GenericObjectPoolConfig genericObjectPoolConfig;

private Pattern p = Pattern.compile("^.+[:]\\d{1,5}\\s*$");

@Override
public JedisCluster getObject() throws Exception {
return jedisCluster;
}

@Override
public Class<?> getObjectType() {
return (this.jedisCluster != null ? this.jedisCluster.getClass() : JedisCluster.class);
}

@Override
public boolean isSingleton() {
return true;
}

private Set<HostAndPort> parseHostAndPort() throws Exception {
try {

Set<HostAndPort> haps = new HashSet<HostAndPort>();
String[] strArray = hostAndPort.split(",");
for (String str : strArray) {

boolean isIpPort = p.matcher(str).matches();

if (!isIpPort) {
throw new IllegalArgumentException("ip 或 port 不合法");
}
String[] ipAndPort = str.split(":");

HostAndPort hap = new HostAndPort(ipAndPort[0],
Integer.parseInt(ipAndPort[1]));
haps.add(hap);
}

return haps;
}
catch (IllegalArgumentException ex) {
throw ex;
}
catch (Exception ex) {
throw new Exception("解析 jedis 配置文件失败", ex);
}
}

public void afterPropertiesSet() throws Exception {
Set<HostAndPort> haps = this.parseHostAndPort();
jedisCluster = new JedisCluster(haps, timeout, maxRedirections, genericObjectPoolConfig);

}

public void setHostAndPort(String hostAndPort) {
this.hostAndPort = hostAndPort;
}

public void setTimeout(int timeout) {
this.timeout = timeout;
}

public void setMaxRedirections(int maxRedirections) {
this.maxRedirections = maxRedirections;
}

public void setGenericObjectPoolConfig(
GenericObjectPoolConfig genericObjectPoolConfig) {
this.genericObjectPoolConfig = genericObjectPoolConfig;
}
}

 

2、配置文件:
<bean name="genericObjectPoolConfig" class="org.apache.commons.pool2.impl.GenericObjectPoolConfig">
<property name="maxWaitMillis" value="${redis.pool.maxWaitMillis}" />
<property name="maxTotal" value="${redis.pool.maxActive}" />
<property name="minIdle" value="${redis.pool.minIdle}" />
<property name="maxIdle" value="${redis.pool.maxIdle}" />
</bean>

<bean id="jedisCluster" class="com.bbw.redis.JedisClusterFactory" init-method="afterPropertiesSet" >
<property name="hostAndPort" value="${redis.pool.host}"/>
<property name="timeout" value="${redis.pool.timeout}" />
<property name="maxRedirections" value="${redis.pool.maxRedirections}" />
<property name="genericObjectPoolConfig" ref="genericObjectPoolConfig" />
</bean>



3、在spring 里面注解使用:

@Autowired
JedisCluster jedisCluster;

转载于:https://www.cnblogs.com/wangjiesheng/p/8586355.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值