- 项目使用的是redis集群,所以用jedis jar。
Jedis的版本是2.9.0,这个版本可以连接有密码的redis集群服务。
- 首先我们需要定义redis操作的接口
public interface IRedisManager {
public Result<DataEntry> get(int nameSpace, Serializable key);
public ResultCode put(int nameSpace, Serializable pkey, Serializable skey, Serializable value);
public Result<DataEntry> get(int nameSpace, Serializable pkey, Serializable skey);
public ResultCode put(int nameSpace, Serializable key, Serializable value);
public ResultCode put(int nameSpace, Serializable key, Serializable value, int bTime);
public boolean setNX(int nameSpace, String key, String value, int timeout);
public void del(int nameSpace, String key);
public long llen(int nameSpace, String key);
public void rpush(int nameSpace, String key, String value);
public void rpush(int nameSpace, String key, String[] value);
public void set(int nameSpace, String key, String value);
public String lpop(int namespace, String key);
public void setObject(int nameSpace, String key, Object value);
public void setObject(int nameSpace, String key, int cal, Object value);
public Object getObject(int namespace, String key);
public void delObject(int namespace, String key);
public long decrBy(int namespace, String key, long num);
public void incrBy(int namespace, String key, long num);
}
- 实现接口,主要的操作就在这个类
- 我们要初始化与redis的连接,用@PostConstructure注解,在类初始化的时候加载连接池,连接redis服务。
- 连接池是GenericObjectPoolConfig
- 对密码auth做判空,创建不同实例。
- 我们要初始化与redis的连接,用@PostConstructure注解,在类初始化的时候加载连接池,连接redis服务。
@PostConstruct
public void initManager(){
for (String string : this.serverStr.split(",")){
this.serverLists.add(string);
HostAndPort hostAndPort = new HostAndPort((string.split(":"))[0], Integer.parseInt((string.split(":"))[1]));
jedisClusterNodes.add(hostAndPort);
}
GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
poolConfig.setMaxTotal(100);
//节点,超时时间,返回值超时时间,失败重试次数,密码,池配置
if(auth==null || auth.equals("${redis.auth}") || auth.isEmpty() ){
jedisCluster = new JedisCluster(jedisClusterNodes,60000,poolConfig);
}else{
jedisCluster = new JedisCluster(jedisClusterNodes,60000,60000,5,auth,poolConfig);
}
}
-
- 对redis服务进行操作
- Put操作
- 对redis服务进行操作
@Override
public ResultCode put(int nameSpace, Serializable key, Serializable value, int bTime)
{
if (bTime > 0)
{
jedisCluster.setex((String) key, bTime, SerializableUtil.getStrFromObj(value));
}
else
{
jedisCluster.set((String) key, SerializableUtil.getStrFromObj(value));
}
return ResultCode.SUCCESS;
}
-
-
- get操作
-
@Override
public Result<DataEntry> get(int nameSpace, Serializable key)
{
String str = jedisCluster.get((String) key);
DataEntry dataEntry = new DataEntry();
Object object = SerializableUtil.getObjFromStr(str);
if (object == null)
{
return new Result<DataEntry>(ResultCode.DATANOTEXSITS);
}
dataEntry.setValue(object);
Result<DataEntry> result = new Result<DataEntry>(ResultCode.SUCCESS, dataEntry);
return result;
}
- 另一种写法
1、定义一个PoolableObjectFactory
package com.sitech.acrdc.session.redis;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.pool.PoolableObjectFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.sitech.acrdc.session.Configuration;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig;
/**
* jredis 集群客户端工厂类
* @author fanrh
*/
public class JedisClusterPoolableObjectFactory implements PoolableObjectFactory {
private static final Logger log = LoggerFactory.getLogger(JedisClusterPoolableObjectFactory.class);
private static Set<HostAndPort> jedisClusterNodes = null;
protected static final int DEFAULT_TIMEOUT = 3000;
protected static final int DEFAULT_MAX_REDIRECTIONS = 5;
private static boolean init = false;
private static final String S = ":";
private static final String S2 = ",";
static {
if (!init) {
synchronized (log) {
if (!init) {
jedisClusterNodes = new HashSet<HostAndPort>();
String[] serverInfos = Configuration.getServers().split(S2);
if (serverInfos != null) {
for (int i = 0; i < serverInfos.length; i++) {
String serverInfo = serverInfos[i];
if (serverInfo.indexOf(S) > 0) {
String[] infos = serverInfo.split(S);
jedisClusterNodes.add(new HostAndPort(infos[0],
Integer.valueOf(infos[1])));
}
}
init = true;
}
}
}
}
}
@Override
public JedisCluster makeObject() {
String password = Configuration.getRedisPassword();
if(!StringUtils.isBlank(password)){
return new JedisCluster(jedisClusterNodes, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, DEFAULT_MAX_REDIRECTIONS, password, new JedisPoolConfig());
}
return new JedisCluster(jedisClusterNodes,DEFAULT_TIMEOUT,DEFAULT_MAX_REDIRECTIONS);
}
public void destroyObject(JedisCluster obj) throws InterruptedException, IOException {
if (obj != null) {
obj.close();
if (log.isInfoEnabled()) {
log.info("JedisCluster 客户端对象被关闭,JedisCluster.sessionId=" + obj.info());
}
}
}
@Override
public void destroyObject(Object obj) throws InterruptedException, IOException {
destroyObject((JedisCluster)obj);
}
public boolean validateObject(JedisCluster obj) {
if (obj != null && obj.getClusterNodes().size() > 0) {
if (log.isDebugEnabled()) {
log.debug("JedisCluster 可用");
}
return true;
}else{
if (log.isInfoEnabled()) {
log.info("JedisCluster 不可用");
}
return false;
}
}
@Override
public boolean validateObject(Object obj) {
return validateObject((JedisCluster)obj);
}
@Override
public void activateObject(Object obj) {
}
@Override
public void passivateObject(Object obj) {
}
}
- 操作类
package com.sitech.acrdc.session.redis;
import java.util.NoSuchElementException;
import org.apache.commons.pool.ObjectPool;
import org.apache.commons.pool.PoolableObjectFactory;
import org.apache.commons.pool.impl.StackObjectPool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.JedisCluster;
import com.sitech.acrdc.session.Configuration;
public final class RedisPoolManager {
private static final Logger log = LoggerFactory
.getLogger(RedisPoolManager.class);
private static RedisPoolManager instance;
private ObjectPool pool;
/**
* 构造方法
*/
private RedisPoolManager() {
PoolableObjectFactory factory = new JedisClusterPoolableObjectFactory();
// 初始化JedisCluster对象
int maxIdle = Configuration.getMaxIdle();
int initIdleCapacity = Configuration.getInitIdleCapacity();
pool = new StackObjectPool(factory, maxIdle, initIdleCapacity);// 对象构建池
if (log.isInfoEnabled()) {
log.info("JedisCluster 初始化完成。");
}
}
/**
* 返回单例的对象
*
* @return
*/
public static RedisPoolManager getInstance() {
if (instance == null) {
synchronized (log) {
if (instance == null) {
instance = new RedisPoolManager();
}
}
}
return instance;
}
/**
* 将JedisCluster对象从对象池中取出
*
* @return
*/
public JedisCluster borrowObject() {
if (pool != null) {
try {
JedisCluster jc = (JedisCluster) pool.borrowObject();
if (log.isDebugEnabled()) {
log.debug("从JedisCluster连接池中返回连接,jc.hashCode ="
+ jc.hashCode());
}
return jc;
} catch (NoSuchElementException ex) {
log.error("从JedisCluster连接池获取连接时发生异常:", ex);
} catch (IllegalStateException ex) {
log.error("从JedisCluster连接池获取连接时发生异常:", ex);
} catch (Exception e) {
log.error("从JedisCluster连接池获取连接时发生异常:", e);
}
}
return null;
}
/**
* 将ZK实例返回对象池
*
* @param zk
*/
public void returnObject(JedisCluster jc) {
if (pool != null && jc != null) {
try {
pool.returnObject(jc);
if (log.isDebugEnabled()) {
log.debug("将连接返回JedisCluster连接池完毕,jc.hashCode ="
+ jc.hashCode());
}
} catch (Exception ex) {
log.error("将连接返回JedisCluster连接池发生异常:", ex);
}
}
}
/**
* 关闭对象池
*/
public void close() {
if (pool != null) {
try {
pool.close();
if (log.isInfoEnabled()) {
log.info("关闭JedisCluster连接池完毕");
}
} catch (Exception ex) {
log.error("关闭JedisCluster连接池完毕", ex);
}
}
}
}