摘要:本文主要向大家介绍了JAVA语言之jedis 集群配置,通过具体的内容向大家展示,希望对大家学习JAVA语言有所帮助。
本文主要向大家介绍了JAVA语言之jedis 集群配置,通过具体的内容向大家展示,希望对大家学习JAVA语言有所帮助。
pom引入jar包
···
redis.clients
jedis
2.9.0
···
### spring配置
```
${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: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:6392
## Redis数据库索引(默认为0)
spring.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;
/**
* 读取redis集群节点
* @author
*
*/
public class JedisClusterFactory implements FactoryBean
, InitializingBean{
private GenericObjectPoolConfig genericObjectPoolConfig;
private JedisCluster jedisCluster;
private int connectionTimeout = 2000;
private int soTimeout = 3000;
private int maxRedirections = 5;
private Set jedisClusterNodes;
public void afterPropertiesSet() throws Exception {
if (jedisClusterNodes == null || jedisClusterNodes.size() == 0) {
throw new NullPointerException("jedisClusterNodes is null.");
}
Set nodesStrSet = new LinkedHashSet();
Set haps = new LinkedHashSet();
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);
}
/**
* 将IP段与端口段拆分为详细的IP:端口
*
* @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 hostList = new ArrayList();
List portList = new ArrayList();
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 rtnValue = new LinkedHashSet();
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 getJedisClusterNodes() {
return jedisClusterNodes;
}
public void setJedisClusterNodes(Set 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;
/**
* jedis集群帮助类
*
Title: JedisClusterHelper
*
Description:
*
* @author
* @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;
}
/**
*
Title: get
*
Description:
* @param format
* @return
*/
public String get(String key) {
return jedisCluster.get(key);
}
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);
}
}
/**
* 自增器
*
Title: incr
*
Description:
* @param key
*/
public int incr(String key) {
int resultIncr = 0;
try {
resultIncr = jedisCluster.incr(key).intValue();
} catch (Exception e) {
log.error("redis集群错误", e);
resultIncr = 0;
}
return resultIncr;
}
public void incrExpire(String key,int seconds){
try {
jedisCluster.incr(key);
jedisCluster.expire(key, seconds);
} catch (Exception e) {
log.error("redis集群错误", e);
}
}
public Map getSnapShots(String key) {
Map resultMap = null;
try {
resultMap = jedisCluster.hgetAll(key);
} catch (Exception e) {
log.error("redis集群错误", e);
}
if (resultMap == null) {
resultMap = new HashMap();
}
return resultMap;
}
public Set smembers(String key) {
Set resultSet = null;
try {
resultSet = jedisCluster.smembers(key);
} catch (Exception e) {
log.error("redis集群错误", e);
}
if (resultSet == null) {
resultSet = new HashSet();
}
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 getKeysAll(String likeKey) {
TreeSet keys = new TreeSet();
try {
if (isNotBlank(likeKey)) {
Map 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 getStrMap(String mapName) {
Map 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..."
+ e.getMessage(), e);
}
return result;
}
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..."
+ e.getMessage(), e);
}
return result;
}
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");
```
本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注编程语言JAVA频道!
您输入的评论内容中包含违禁敏感词
我知道了
请输入正确的手机号码
请输入正确的验证码
您今天的短信下发次数太多了,明天再试试吧!
我们会在第一时间安排职业规划师联系您!
您也可以联系我们的职业规划师咨询:
版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
沪公网安备 31011502005948号