本文共 11767 字,大约阅读时间需要 39 分钟。
···### spring配置 redis.clients jedis 2.9.0
${spring.redis.cluster.nodes1} ${spring.redis.cluster.nodes2} ${spring.redis.cluster.nodes3} ${spring.redis.cluster.nodes4} ${spring.redis.cluster.nodes5} ${spring.redis.cluster.nodes6}
### redis.properties配置文件
###redis集群
spring.redis.cluster.nodes1=127.0.0.1:6380spring.redis.cluster.nodes2=127.0.0.1:6381spring.redis.cluster.nodes3=127.0.0.1:6382spring.redis.cluster.nodes4=127.0.0.1:6390spring.redis.cluster.nodes5=127.0.0.1:6391spring.redis.cluster.nodes6=127.0.0.1:6392spring.redis.database=0
spring.redis.timeout=60000
spring.redis.maxRedirects=3
spring.redis.pool.max-active=300
spring.redis.pool.max-wait=-1
spring.redis.pool.max-idle=100
spring.redis.pool.min-idle=20
### 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;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");
转载于:https://blog.51cto.com/jtech/2336286