<!-- redis start --> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.9.0</version> </dependency> <!-- redis end --> ··· ### spring配置
<bean id="myJedisClusterHelper" class="com.redis.JedisClusterHelper"> <property name="jedisCluster" ref="myJedisClusterFactory" /> </bean> <!-- redis集羣 --> <bean id="myJedisClusterFactory" class="com.redis.JedisClusterFactory"> <property name="connectionTimeout" value="3000" /> <property name="soTimeout" value="3000" /> <property name="maxRedirections" value="5" /> <property name="genericObjectPoolConfig" ref="myJedisClusterPoolConfig" /> <property name="jedisClusterNodes"> <set> <!-- 生產環境 --> <value>${spring.redis.cluster.nodes1}</value> <value>${spring.redis.cluster.nodes2}</value> <value>${spring.redis.cluster.nodes3}</value> <value>${spring.redis.cluster.nodes4}</value> <value>${spring.redis.cluster.nodes5}</value> <value>${spring.redis.cluster.nodes6}</value> </set> </property> </bean> <!-- redis3.2集羣配置 --> <bean id="myJedisClusterPoolConfig" class="redis.clients.jedis.JedisPoolConfig"> <property name="maxTotal" value="50" /> <property name="maxIdle" value="5" /> <property name="maxWaitMillis" value="100000" /> <property name="testOnBorrow" value="true" /> </bean>
### redis.properties配置文件
###redis集羣
spring.redis.cluster.nodes1=127.0.0.1:6380
spring.redis.cluster.nodes2=127.0.0.1:6381
spring.redis.cluster.nodes3=127.0.0.1:6382
spring.redis.cluster.nodes4=127.0.0.1:6390
spring.redis.cluster.nodes5=127.0.0.1:6391
spring.redis.cluster.nodes6=127.0.0.1:6392java
spring.redis.database=0node
spring.redis.timeout=60000es6
spring.redis.maxRedirects=3redis
spring.redis.pool.max-active=300spring
spring.redis.pool.max-wait=-1數據庫
spring.redis.pool.max-idle=100apache
spring.redis.pool.min-idle=20ide
### JedisClusterFactory.java集羣工廠類
package com.redis;工具
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;this
import org.apache.commons.lang.StringUtils;
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;
/**
*/
public class JedisClusterFactory implements FactoryBean<JedisCluster>, InitializingBean{
private GenericObjectPoolConfig genericObjectPoolConfig;
private JedisCluster jedisCluster;
private int connectionTimeout = 2000;
private int soTimeout = 3000;
private int maxRedirections = 5;
private Set<String> jedisClusterNodes;
public void afterPropertiesSet() throws Exception {
if (jedisClusterNodes == null || jedisClusterNodes.size() == 0) {
throw new NullPointerException("jedisClusterNodes is null.");
}
Set<String> nodesStrSet = new LinkedHashSet<String>();
Set<HostAndPort> haps = new LinkedHashSet<HostAndPort>();
for (String node : jedisClusterNodes) {
if (StringUtils.contains(node, "-")) {
nodesStrSet.addAll(Arrays.asList(convertHostIpSectionToList(node)));
} else {
nodesStrSet.add(node);
}
}
for (String node : nodesStrSet) {
String[] arr = node.split(":");
if (arr.length != 2) {
throw new ParseException("node address error !", node.length() - 1);
}
haps.add(new HostAndPort(arr[0], Integer.valueOf(arr[1])));
}
jedisCluster = new JedisCluster(haps, connectionTimeout, maxRedirections, genericObjectPoolConfig);
}
/**
@param addresses IP段\端口段,格式爲:xxx.xxx.xxx.xxx-xxx:xxxxx-xxxxx
*/
private String[] convertHostIpSectionToList(String addresses) {
if (StringUtils.isBlank(addresses)) {
throw new IllegalArgumentException("The addresses parameter must not be null.");
}
String[] split = StringUtils.split(addresses, ":");
String hostSection = split[0], portSection = split[1];
hostSection = hostSection.trim();
portSection = portSection.trim();
List<String> hostList = new ArrayList<String>();
List<Integer> portList = new ArrayList<Integer>();
if (StringUtils.countMatches(hostSection, ".") != 3) {
throw new IllegalArgumentException("The hostSection [" + hostSection + "] format is incorrect.");
}
int hostMatches = StringUtils.countMatches(hostSection, "-");
if (hostMatches == 0) {
hostList.add(hostSection);
} else if (hostMatches == 1) {
String hostSectionLast = StringUtils.substringAfterLast(hostSection, ".");
String hostFixed = StringUtils.replace(hostSection, hostSectionLast, StringUtils.EMPTY);
String[] hostSections = StringUtils.split(hostSectionLast, "-");
if (hostSections.length != 2) {
throw new IllegalArgumentException("The hostSection [" + hostSection + "] format is incorrect.");
}
int start = Integer.valueOf(hostSections[0]), end = Integer.valueOf(hostSections[1]);
for (int i = start; i <= end; i++) {
hostList.add(String.valueOf(hostFixed + i));
}
} else {
throw new IllegalArgumentException("The hostSection [" + hostSection + "] format is incorrect.");
}
String[] portSections = StringUtils.split(portSection, "-");
if (portSections.length == 1) {
portList.add(Integer.valueOf(portSections[0]));
} else if (portSections.length == 2) {
int start = Integer.valueOf(portSections[0]), end = Integer.valueOf(portSections[1]);
for (int port = start; port <= end; port++) {
portList.add(port);
}
} else {
throw new IllegalArgumentException("The portSection [" + portSection + "] format is incorrect.");
}
Set<String> rtnValue = new LinkedHashSet<String>();
for (String host : hostList) {
for (Integer port : portList) {
rtnValue.add(String.format("%s:%d", host, port));
}
}
return rtnValue.toArray(new String[rtnValue.size()]);
}
public JedisCluster getObject() throws Exception {
return jedisCluster;
}
public Class<?> getObjectType() {
return (this.jedisCluster != null ? this.jedisCluster.getClass() : JedisCluster.class);
}
public boolean isSingleton() {
return true;
}
public GenericObjectPoolConfig getGenericObjectPoolConfig() {
return genericObjectPoolConfig;
}
public void setGenericObjectPoolConfig(GenericObjectPoolConfig genericObjectPoolConfig) {
this.genericObjectPoolConfig = genericObjectPoolConfig;
}
public JedisCluster getJedisCluster() {
return jedisCluster;
}
public void setJedisCluster(JedisCluster jedisCluster) {
this.jedisCluster = jedisCluster;
}
public int getConnectionTimeout() {
return connectionTimeout;
}
public void setConnectionTimeout(int connectionTimeout) {
this.connectionTimeout = connectionTimeout;
}
public int getSoTimeout() {
return soTimeout;
}
public void setSoTimeout(int soTimeout) {
this.soTimeout = soTimeout;
}
public int getMaxRedirections() {
return maxRedirections;
}
public void setMaxRedirections(int maxRedirections) {
this.maxRedirections = maxRedirections;
}
public Set<String> getJedisClusterNodes() {
return jedisClusterNodes;
}
public void setJedisClusterNodes(Set<String> jedisClusterNodes) {
this.jedisClusterNodes = jedisClusterNodes;
}
}
### JedisClusterHelper.java集羣幫助工具類
package com.redis;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;
/**
@date 2018-7-2
*/
public class JedisClusterHelper{
private static Logger log = LoggerFactory.getLogger(JedisClusterHelper.class);
private JedisCluster jedisCluster;
public JedisCluster getJedisCluster() {
return jedisCluster;
}
public void setJedisCluster(JedisCluster jedisCluster) {
this.jedisCluster = jedisCluster;
}
/**
public void set(String key,String value) {
jedisCluster.set(key, value);
}
public void expire(String key,int seconds) {
try {
jedisCluster.expire(key, seconds);
} catch (Exception e) {
log.error("redis集羣錯誤", e);
}
}
public void setExpire(String key,String value,int seconds){
try {
jedisCluster.set(key, value);
jedisCluster.expire(key, seconds);
} catch (Exception e) {
log.error("redis集羣錯誤", e);
}
}
public boolean exists(String key) {
boolean resultExists = false;
try {
resultExists = jedisCluster.exists(key);
} catch (Exception e) {
log.error("redis集羣錯誤", e);
resultExists = false;
}
return resultExists;
}
public void del(String key) {
try{
jedisCluster.del(key);
} catch (Exception e) {
log.error("redis集羣錯誤", e);
}
}
/**
public void incrExpire(String key,int seconds){
try {
jedisCluster.incr(key);
jedisCluster.expire(key, seconds);
} catch (Exception e) {
log.error("redis集羣錯誤", e);
}
}
public Map<String, String> getSnapShots(String key) {
Map resultMap = null;
try {
resultMap = jedisCluster.hgetAll(key);
} catch (Exception e) {
log.error("redis集羣錯誤", e);
}
if (resultMap == null) {
resultMap = new HashMap<String, String>();
}
return resultMap;
}
public Set<String> smembers(String key) {
Set<String> resultSet = null;
try {
resultSet = jedisCluster.smembers(key);
} catch (Exception e) {
log.error("redis集羣錯誤", e);
}
if (resultSet == null) {
resultSet = new HashSet<String>();
}
return resultSet;
}
public Long expireAt(String key, long unixTime) {
try {
return jedisCluster.expireAt(key, unixTime);
} catch (Exception e) {
log.error("redis集羣錯誤", e);
}
return null;
}
public Set<String> getKeysAll(String likeKey) {
TreeSet<String> keys = new TreeSet<String>();
try {
if (isNotBlank(likeKey)) {
Map<String, JedisPool> clusterNodes = jedisCluster.getClusterNodes();
log.info("getKeysAll start:" + likeKey);
for(String k : clusterNodes.keySet()){
JedisPool jp = clusterNodes.get(k);
Jedis connection = jp.getResource();
try {
keys.addAll(connection.keys(likeKey));
} catch(Exception e){
log.error("Getting keys error: {}", e);
} finally{
log.debug("Connection closed.");
connection.close();//用完必定要close這個連接!!!
}
}
log.info("getKeysAll end:" + likeKey + "keys.size:" + keys.size());
}
} catch (Exception e) {
log.error("redis集羣錯誤", e);
}
return keys;
}
public Map<String, String> getStrMap(String mapName) {
Map<String, String> mapStr = null;
try {
if (mapName != null && !"".equals(mapName)) {
// 獲取List下的全部值
mapStr = jedisCluster.hgetAll(mapName);
}
} catch (Exception e) {
log.error("redis集羣錯誤",e);
}
return mapStr;
}
public Object getObj(String key) {
if (key != null && !"".equals(key)) {
byte[] byteKey = key.getBytes();
byte[] result = this.getByte(byteKey);// 獲取byte類型的數據
Object obj = null;
if (result != null) {
obj = SerializeUtil.unserialize(result); } return obj; } return null;
}
public byte[] getByte(byte[] key) {
try {
return jedisCluster.get(key);
} catch (Exception e) {
log.error("getByte:[key=" + key + "] occur exception..." + e.getMessage(), e);
}
return null;
}
public long setStrMap(String mapName, String key, String value) {
long result = -1;
try {
if (mapName != null && !"".equals(mapName)) {
// 向set中存放值
result = jedisCluster.hset(mapName, key, value);
}
} catch (Exception e) {
log.error("setStrMap:[mapName=" + mapName + ";key=" + key + ";value=" + value + "] occur exception..."
public long delStrMap(String mapName, String key) {
long result = -1;
try {
if (mapName != null && !"".equals(mapName)) {
// 向set中存放值
result = jedisCluster.hdel(mapName, key);
}
} catch (Exception e) {
log.error("setStrMap:[mapName=" + mapName + ";key=" + key + "] occur exception..."
public static boolean isBlank(String str) {
int strLen;
if (str == null || (strLen = str.length()) == 0)
return true;
for (int i = 0; i < strLen; i++)
if (!Character.isWhitespace(str.charAt(i)))
return false;
return true;
}
public static boolean isNotBlank(String str) {
return !isBlank(str);
}
}
### 使用方法
@Autowired
private JedisClusterHelper myJedisClusterHelper;
myJedisClusterHelper.set("testkey","testvalue");