1,配置文件
redis:
clusterNodes:
- 10.108.6.90:6179
- 10.108.6.90:6279
- 10.108.6.90:6379
- 10.108.6.90:6479
- 10.108.6.90:6579
- 10.108.6.90:6679
password: Allways_123
expireSeconds: 120
commandTimeout: 10000 #redis操作的超时时间
pool:
#最大连接数
maxActive: 5000
#最大空闲连接数
maxIdle: 30
#最小空闲连接数
minIdle: 5
#获取连接最大等待时间 ms #default -1
maxWait: 10000
#最大尝试连接数
maxAttempts: 1
2,java属性对象创建
@Component
@ConfigurationProperties(prefix = "spring.redis")
public class RedisProperties {
private int expireSeconds;
private List clusterNodes = new ArrayList();
private String password;
private int commandTimeout;
private Map pool = new HashMap<>();
public int getExpireSeconds() {
return expireSeconds;
}
public void setExpireSeconds(int expireSeconds) {
this.expireSeconds = expireSeconds;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getCommandTimeout() {
return commandTimeout;
}
public void setCommandTimeout(int commandTimeout) {
this.commandTimeout = commandTimeout;
}
public Map getPool() {
return pool;
}
public void setPool(Map pool) {
this.pool = pool;
}
public List getClusterNodes() {
return clusterNodes;
}
public void setClusterNodes(List clusterNodes) {
this.clusterNodes = clusterNodes;
}
}
3,java获取配置文件信息
@Configuration
public class JedisClusterConfig {
@Autowired
private RedisProperties redisProperties;
/**
* 返回的JedisCluster是单例的,并且可以直接注入到其他类中去使用
* @return
*/
@Bean
public JedisCluster getJedisCluster() {
Set nodes = new HashSet<>();
List clusterNodes = redisProperties.getClusterNodes();
for (String ipPort : clusterNodes) {
String[] ipPortPair = ipPort.split(":");
nodes.add(new HostAndPort(ipPortPair[0].trim(), Integer.valueOf(ipPortPair[1].trim())));
}
GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
poolConfig.setMaxTotal(redisProperties.getPool().get("maxActive"));//最大连接数
poolConfig.setMaxIdle(redisProperties.getPool().get("maxIdle"));//最大空闲连接数
poolConfig.setMinIdle(redisProperties.getPool().get("minIdle"));//最小空闲连接数
poolConfig.setMaxWaitMillis(redisProperties.getPool().get("maxWait").longValue());//连接最大等待时间
return new JedisCluster(nodes,redisProperties.getCommandTimeout(),redisProperties.getCommandTimeout(),
redisProperties.getPool().get("maxAttempts"),redisProperties.getPassword() ,poolConfig);//需要密码连接的创建对象方式
}
}
4,工具类
package com.anji.allways.common.redis;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPool;
import java.io.UnsupportedEncodingException;
import java.util.Collections;
import java.util.Date;
import java.util.Map;
import java.util.TreeSet;
/**
*
* redis工具类
*
*
* @author 超级家明
* @version $Id: RedisUtils.java, v 0.1 2018年7月6日 下午3:39:13 超级家明 Exp $
*/
@Component
public class RedisUtils {
public static String REDIS_RECEIVE = "receive_";
private static String redisCode = "utf-8";
public static String REDIS_OURINV = "outinv_synchronized";
private static final Long RELEASE_SUCCESS = 1L;
public final static Logger logger = LogManager.getLogger(RedisUtils.class);
@Autowired
private JedisCluster jedisCluster;
/**
* 设置缓存
*
* @param key 缓存key
* @param value 缓存value
*/
public void set(String key, String value) {
jedisCluster.set(key, value);
}
/**
* 设置缓存,并且自己指定过期时间
*
* @param key
* @param value
* @param expireTime 过期时间
*/
public void setWithExpireTime(String key, String value, int expireTime) {
jedisCluster.setex(key, expireTime, value);
}
/**
* 设置失效时间
*
* @param key
* @param expireTime
*/
public void expire(String key, int expireTime) {
jedisCluster.setex(key, expireTime, jedisCluster.get(key));
}
/**
* 获取指定key的缓存
*
* @param key
*/
public String get(String key) {
String value = jedisCluster.get(key);
return value;
}
//解决redis异常
public String getThrowRedis(String key) {
try {
get(key);
} catch (Exception e) {
return null;
}
return get(key);
}
/**
* 设置缓存对象
*
* @param key 缓存key
* @param obj 缓存value
* @param expireTime 过期时间
*/
public void setObject(String key, T obj, int expireTime) {
jedisCluster.setex(key, expireTime, JSON.toJSONString(obj));
}
/**
* 获取指定key的缓存
*
* @param key---JSON.parseObject(value, User.class);
*/
public String getObject(String key) {
return jedisCluster.get(key);
}
/**
* 判断当前key值 是否存在
*
* @param key
*/
public boolean hasKey(String key) {
return jedisCluster.exists(key);
}
/**
* 删除指定key的缓存
*
* @param key
*/
public void delete(String key) {
jedisCluster.del(key);
}
/**
*
* 上锁
*
*
* @param key
*/
public synchronized void lock(String key) {
if (StringUtils.isBlank(key)) {
return;
}
this.set(key, new Date().toString());
}
/**
*
* 上锁
*
*
* @param key
*/
public synchronized void lockWithExpireTime(String key, int seconds) {
if (StringUtils.isBlank(key)) {
return;
}
jedisCluster.setex(key, seconds, new Date().toString());
}
/**
*
* 判断key是否被锁住了
*
*
* @param key
* @return
*/
public synchronized Boolean isLock(String key) {
if (StringUtils.isBlank(key)) {
return false;
}
String stringDate = this.get(key);
if (StringUtils.isBlank(stringDate)) {
return false;
}
return true;
}
/**
*
* 解锁
*
*
* @param key
*/
public synchronized void unLock(String key) {
if (StringUtils.isBlank(key)) {
return;
}
this.delete(key);
}
/**
*
* 递增
*
*
* @param key
* @param by
* @return
*/
public Long incr(String key, Long by) {
//默认原子操作
if (by == null) {
by = 1l;
}
return jedisCluster.incrBy(key, by);
}
/**
*
*
*
*
* @param key
* @param value
* @param liveTime
*/
public void set(String key, Object value, Long liveTime) {
try {
jedisCluster.setex(key.getBytes(redisCode), liveTime.intValue(), value.toString().getBytes(redisCode));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
/**
*
* 批量删除keys
*
*
* @param keys
*/
public void delKeys(String[] keys) {
if(keys != null) {
for (String key : keys) {
Long del = jedisCluster.del(key);
System.out.println(del);
}
}
}
public void unlockValue(String keys, String value) {
String lockValue = jedisCluster.get(keys);
if (lockValue.equals(value)){
jedisCluster.del(keys);
}
}
public String[] keys(String pattern){
TreeSet keys = new TreeSet<>();
Map clusterNodes = jedisCluster.getClusterNodes();
for(String k : clusterNodes.keySet()){
logger.debug("Getting keys from: {}", k);
JedisPool jp = clusterNodes.get(k);
Jedis connection = jp.getResource();
try {
keys.addAll(connection.keys(pattern));
} catch(Exception e){
logger.error("Getting keys error: {}", e);
} finally{
logger.debug("Connection closed.");
connection.close();//用完一定要close这个链接!!!
}
}
return keys.toArray(new String[] {});
}
/**
* 设置缓存
* @param key 缓存key
* @param value 缓存value
*/
public Long setnx(String key, String value) {
return jedisCluster.setnx(key, value);
}
/**
*
* 上锁
*
*
* @param key
*/
public synchronized boolean locknx(String key){
if(StringUtils.isBlank(key)){
return false;
}
Long result = this.setnx(key, new Date().toString());
if(result.equals(0L)){//如果返回0 则该key已经存在
return false;
}
return true;
}
/**
*
* 上锁
*
*
* @param key
*/
public synchronized boolean locknx(String key, String value){
if(StringUtils.isBlank(key)){
return false;
}
Long result = this.setnx(key, value);
if(result.equals(0L)){//如果返回0 则该key已经存在
return false;
}
this.expire(key, 60*3);//设置失效时间3分钟
return true;
}
public synchronized boolean lock(String lockKey,String requestId,int expireTime) {
String result=jedisCluster.set(lockKey, requestId, "NX", "PX", expireTime);
if("OK".equals(result)) {
return true;
}
return false;
}
public synchronized boolean releaseLock(String lockKey,String requestId) {
String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
Object result = jedisCluster.eval(script, Collections.singletonList(lockKey), Collections.singletonList(requestId));
if (RELEASE_SUCCESS.equals(result)) {
return true;
}
return false;
}
}