前言
...................
使用Jedis连接Redis集群
- spring-redis配置文件:
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd">
<!-- jedis 配置 -->
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
<!--最大空闲数 -->
<property name="maxIdle" value="${redis.maxIdle}" />
<!--最大建立连接等待时间 -->
<property name="maxWaitMillis" value="${redis.maxWait}" />
<!--是否在从池中取出连接前进行检验,如果检验失败,则从池中去除连接并尝试取出另一个 -->
<property name="testOnBorrow" value="${redis.testOnBorrow}" />
<property name="maxTotal" value="${redis.maxTotal}" />
<property name="minIdle" value="${redis.minIdle}" />
</bean>
<bean id="jedisCluster" class="com.zat.umpg.redis.SimpleJedisCluster" >
<property name="address">
<list>
<value>${cluster1.host.port}</value>
<value>${cluster2.host.port}</value>
<value>${cluster3.host.port}</value>
<value>${cluster4.host.port}</value>
<value>${cluster5.host.port}</value>
<value>${cluster6.host.port}</value>
</list>
</property>
<property name="addressKeyPrefix" value="cluster" />
<property name="timeout" value="${redis.timeout}" />
<property name="maxRedirections" value="6" />
<property name="genericObjectPoolConfig" ref="poolConfig" />
</bean>
</beans>
- jedisCluster初始化类:
package com.zat.umpg.redis;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Pattern;
public class SimpleJedisCluster implements FactoryBean<JedisCluster>, InitializingBean {
private JedisCluster jedisCluster;
private Integer timeout;
private Integer maxRedirections;
private GenericObjectPoolConfig poolConfig;
private Pattern p = Pattern.compile("^.+[:]\d{1,5}\s*$");
private String[] address;
public JedisCluster getObject() throws Exception {
return jedisCluster;
}
public Class<? extends JedisCluster> getObjectType() {
return (this.jedisCluster != null ? this.jedisCluster.getClass() : JedisCluster.class);
}
public boolean isSingleton() {
return true;
}
private Set<HostAndPort> parseHostAndPort() {
try {
Set<HostAndPort> haps = new HashSet<HostAndPort>();
if (address != null && address.length > 0) {
for (String val : address) {
boolean isIpPort = p.matcher(val).matches();
String[] ipAndPort = val.split(":");
if (!isIpPort) {
throw new IllegalArgumentException("ip 或 port 不合法");
}
HostAndPort hap = new HostAndPort(ipAndPort[0],
Integer.parseInt(ipAndPort[1]));
haps.add(hap);
}
}
return haps;
} catch (IllegalArgumentException ex) {
ex.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public void afterPropertiesSet() throws Exception {
Set<HostAndPort> haps = this.parseHostAndPort();
jedisCluster = new JedisCluster(haps, timeout, maxRedirections, poolConfig);
}
public void setTimeout(int timeout) {
this.timeout = timeout;
}
public void setMaxRedirections(int maxRedirections) {
this.maxRedirections = maxRedirections;
}
public void setGenericObjectPoolConfig(GenericObjectPoolConfig poolConfig) {
this.poolConfig = poolConfig;
}
public String[] getAddress() {
return address;
}
public void setAddress(String[] address) {
this.address = address;
}
}
- 具体redis操作类:
package com.zat.umpg.redis;
import com.zat.collect.common.TraceClass;
import com.zat.collect.common.TraceMethod;
import com.zat.collect.common.TraceType;
import redis.clients.jedis.JedisCluster;
import javax.annotation.Resource;
public class RedisDaoImpl implements RedisDao {
@Resource(name="jedisCluster")
private JedisCluster jedisCluster;
@TraceMethod(type = TraceType.REDIS)
public Long incr(String key,int expirt) {
long index = jedisCluster.incr(key);
if (expirt != 0) {
jedisCluster.expire(key, expirt);
}
return index;
}
public Long decr(String key,int expirt) {
long index = jedisCluster.decr(key);
if (expirt != 0) {
jedisCluster.expire(key, expirt);
}
return index;
}
@TraceMethod(type = TraceType.REDIS)
public String setex(String key,String value,int expireSecond){
return jedisCluster.setex(key,expireSecond,value);
}
@TraceMethod(type = TraceType.REDIS)
public Long setex(String key,String value){
return jedisCluster.setnx(key,value);
}
@TraceMethod(type = TraceType.REDIS)
public String get(String key){
return jedisCluster.get(key);
}
@TraceMethod(type = TraceType.REDIS)
public Long del(final String key){
return jedisCluster.del(key);
}
@TraceMethod(type = TraceType.REDIS)
public boolean hasKey(String key){
return jedisCluster.exists(key);
}
}
- 单元测试类:
package com.zat.umpg.bus.redis;
import com.zat.redis.util.RedisClusterUtils;
import com.zat.sproxy.logger.Logger;
import com.zat.sproxy.logger.LoggerFactory;
import junit.framework.TestCase;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import redis.clients.jedis.ScanParams;
import redis.clients.jedis.ScanResult;
import redis.clients.jedis.Tuple;
import javax.servlet.annotation.WebListener;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Redis集群单元测试类.
*
* @author weixiong.cao
* @date 22/04/2020
* @version 1.0
*/
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@WebListener
@ContextConfiguration(locations={"file:src/main/webapp/WEB-INF/context-*.xml","classpath:conf/*/*.xml"})
public class RedisClusterUtilTest extends TestCase {
private static Logger logger = LoggerFactory.getLogger(RedisClusterUtilTest.class);
@Before
public void before() throws Exception {
}
@After
public void after() throws Exception {
}
@Resource(name="jedisCluster")
private JedisCluster jedisCluster;
@Test
public void testGetByApp() {
String key = "redis_app_test";
String value = "redis_app_test is change";
jedisCluster.set(key, value);
final String redisValue = jedisCluster.get(key);
logger.info("redis_app_test={}", redisValue);
assertEquals("", value, redisValue);
}
}