《在 Web 项目中使用 Redis 快速构建系统缓存》
Redis服务器的部署方式可分为单机版和集群版的方式,使用Jedis的对应访问接口也相应不用。如何使用Jedis操作两种不同部署方式的Redis数据,以及在web工程里如何快速的切换两种不同的访问方式,是本文要介绍的主要内容。
JedisClient与JedisClusterClient都实现了JedisClinet接口,接口里定义了操作redis的各种方法,这两个Client实现类分别对应着单机和集群两种访问方式。RedisOperate类是供其它类调用的Redis操作类,它持有IJedisClient接口的实现类对象,这个对象由spring注入,具体使用哪种连接方式取决于注入的IJedisClient的实现类类型。这里使用的是策略模式。
JedisClusterFactory实现了org.springframework.beans.factory.FactoryBean和org.springframework.beans.factory.InitializingBean接口,用于为JedisClusterClient提供redis.clients.jedis.JedisCluster操作类。JedisClient的操作类是redis.clients.jedis.Jedis,从redis.clients.jedis.JedisPool类中获取。
Spring 配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd"
default-lazy-init="true">
<description>Jedis 配置文件</description>
<!-- 加载配置属性文件 -->
<context:property-placeholder ignore-unresolvable="true" location="classpath:jeeplus.properties" />
<!-- redis 单机连接方案 -->
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxIdle" value="300" /> <!-- 最大能够保持idle状态的对象数 -->
<property name="maxTotal" value="60000" /> <!-- 最大分配的对象数 -->
<property name="testOnBorrow" value="true" /> <!-- 当调用borrow Object方法时,是否进行有效性检查 -->
</bean>
<bean id="jedisSingleClient" class="redis.clients.jedis.JedisPool">
<constructor-arg index="0" ref="jedisPoolConfig" />
<constructor-arg index="1" value="${redis.host}" />
<constructor-arg index="2" value="${redis.port}" type="int" />
</bean>
<!-- redis 的伪集群连接方案 -->
<bean name="genericObjectPoolConfig" class="org.apache.commons.pool2.impl.GenericObjectPoolConfig">
<property name="maxWaitMillis" value="-1" />
<property name="maxTotal" value="8" />
<property name="minIdle" value="0" />
<property name="maxIdle" value="8" />
</bean>
<bean id="jedisCluster" class="com.jeeplus.common.redis.JedisClusterFactory">
<property name="connectionTimeout" value="3000" />
<property name="soTimeout" value="3000" />
<property name="maxRedirections" value="5" />
<property name="genericObjectPoolConfig" ref="genericObjectPoolConfig" />
<property name="jedisClusterNodes">
<set>
<value>192.168.78.137:8000</value>
<value>192.168.78.137:8001</value>
<value>192.168.78.137:8002</value>
</set>
</property>
</bean>
<!--
具体连接方式由jedisClient的ref属性决定
可选项为jedisClusterClient、jedisSingleClient
-->
<bean name="redisOperate" class="com.jeeplus.common.redis.RedisOperate">
<property name="jedisClient" ref="jedisSingleClient" />
</bean>
</beans>
JedisClient 接口:
/**
* jedis 接口
* <p> @ClassName : JedisClient </p>
* <p> @Description : TODO </p>
* @Author : HuaZai
* @ContactInformation : 1461522031@qq.com/huazai6789@aliyun.com
* @Date : 2018年1月19日 下午3:02:03
* @Version : V1.0.0
*
* @param
*/
public interface JedisClient {
/**
* 获取缓存
* @param key 键
* @return 值
*/
public String get(String key);
/**
* 获取缓存
* @param key 键
* @return 值
*/
public Object getObject(String key);
/**
* 设置缓存
* @param key 键
* @param value 值
* @param cacheSeconds 超时时间,0为不超时
* @return
*/
public String set(String key, String value, int cacheSeconds);
/**
* 设置缓存
* @param key 键
* @param value 值
* @param cacheSeconds 超时时间,0为不超时
* @return
*/
public String setObject(String key, Object value, int cacheSeconds);
/**
* 获取List缓存
* @param key 键
* @return 值
*/
public List<String> getList(String key);
/**
* 获取List缓存
* @param key 键
* @return 值
*/
public List<Object> getObjectList(String key);
/**
* 设置List缓存
* @param key 键
* @param value 值
* @param cacheSeconds 超时时间,0为不超时
* @return
*/
public long setList(String key, List<String> value, int cacheSeconds);
/**
* 设置List缓存
* @param key 键
* @param value 值
* @param cacheSeconds 超时时间,0为不超时
* @return
*/
public long setObjectList(String key, List<Object> value, int cacheSeconds);
/**
* 向List缓存中添加值
* @param key 键
* @param value 值
* @return
*/
public long listAdd(String key, String... value);
/**
* 向List缓存中添加值
* @param key 键
* @param value 值
* @return
*/
public long listObjectAdd(String key, Object... value);
/**
* 获取缓存
* @param key 键
* @return 值
*/
public Set<String> getSet(String key);
/**
* 获取缓存
* @param key 键
* @return 值
*/
public Set<Object> getObjectSet(String key);
/**
* 设置Set缓存
* @param key 键
* @param value 值
* @param cacheSeconds 超时时间,0为不超时
* @return
*/
public long setSet(String key, Set<String> value, int cacheSeconds);
/**
* 设置Set缓存
* @param key 键
* @param value 值
* @param cacheSeconds 超时时间,0为不超时
* @return
*/
public long setObjectSet(String key, Set<Object> value, int cacheSeconds);
/**
* 向Set缓存中添加值
* @param key 键
* @param value 值
* @return
*/
public long setSetAdd(String key, String... value);
/**
* 向Set缓存中添加值
* @param key 键
* @param value 值
* @return
*/
public long setSetObjectAdd(String key, Object... value);
/**
* 获取Map缓存
* @param key 键
* @return 值
*/
public Map<String, String> getMap(String key);
/**
* 获取Map缓存
* @param key 键
* @return 值
*/
public Map<String, Object> getObjectMap(String key);
/**
* 设置Map缓存
* @param key 键
* @param value 值
* @param cacheSeconds 超时时间,0为不超时
* @return
*/
public String setMap(String key, Map<String, String> value, int cacheSeconds);
/**
* 设置Map缓存
* @param key 键
* @param value 值
* @param cacheSeconds 超时时间,0为不超时
* @return
*/
public String setObjectMap(String key, Map<String, Object> value,
int cacheSeconds);
/**
* 向Map缓存中添加值
* @param key 键
* @param value 值
* @return
*/
public String mapPut(String key, Map<String, String> value);
/**
* 向Map缓存中添加值
* @param key 键
* @param value 值
* @return
*/
public String mapObjectPut(String key, Map<String, Object> value);
/**
* 移除Map缓存中的值
* @param key 键
* @param value 值
* @return
*/
public long mapRemove(String key, String mapKey);
/**
* 移除Map缓存中的值
* @param key 键
* @param value 值
* @return
*/
public long mapObjectRemove(String key, String mapKey);
/**
* 判断Map缓存中的Key是否存在
* @param key 键
* @param value 值
* @return
*/
public boolean mapExists(String key, String mapKey);
/**
* 判断Map缓存中的Key是否存在
* @param key 键
* @param value 值
* @return
*/
public boolean mapObjectExists(String key, String mapKey);
/**
* 删除缓存
* @param key 键
* @return
*/
public long del(String key);
/**
* 删除缓存
* @param key 键
* @return
*/
public long delObject(String key);
/**
* 缓存是否存在
* @param key 键
* @return
*/
public boolean exists(String key);
/**
* 缓存是否存在
* @param key 键
* @return
*/
public boolean existsObject(String key);
}
JedisSingleClient 实现类:
/**
* redis 单机版连接客户端
* <p>
*
* @ClassName : JedisSingleClient
* </p>
* <p>
* @Description : TODO
* </p>
*
* @Author : HuaZai
* @ContactInformation : 1461522031@qq.com/huazai6789@aliyun.com
* @Date : 2018年1月19日 下午2:59:23
* @Version : V1.0.0
*
* @param
*/
public class JedisSingleClient implements JedisClient {
private static Logger logger = LoggerFactory.getLogger(JedisSingleClient.class);
private JedisPool jedisPool = SpringContextHolder.getBean(JedisPool.class);
/**
* 获取缓存
*
* @param key
* 键
* @return 值
*/
public String get(String key) {
String value = null;
Jedis jedis = null;
try {
jedis = getResource();
if (jedis.exists(key)) {
value = jedis.get(key);
value = StringUtils.isNotBlank(value) && !"nil".equalsIgnoreCase(value) ? value : null;
logger.debug("get {} = {}", key, value);
}
} catch (Exception e) {
logger.warn("get {} = {}", key, value, e);
} finally {
returnResource(jedis);
}
return value;
}
/**
* 获取缓存
*
* @param key
* 键
* @return 值
*/
public Object getObject(String key) {
Object value = null;
Jedis jedis = null;
try {
jedis = getResource();
if (jedis.exists(getBytesKey(key))) {
value = toObject(jedis.get(getBytesKey(key)));
logger.debug("getObject {} = {}", key, value);
}
} catch (Exception e) {
logger.warn("getObject {} = {}", key, value, e);
} finally {
returnResource(jedis);
}
return value;
}
/**
* 设置缓存
*
* @param key
* 键
* @param value
* 值
* @param cacheSeconds
* 超时时间,0为不超时
* @return
*/
public String set(String key, String value, int cacheSeconds) {
String result = null;
Jedis jedis = null;
try {
jedis = getResource();
result = jedis.set(key, value);
if (cacheSeconds != 0) {
jedis.expire(key, cacheSeconds);
}
logger.debug("set {} = {}", key, value);
} catch (Exception e) {
logger.warn("set {} = {}", key, value, e);
} finally {
returnResource(jedis);
}
return result;
}
/**
* 设置缓存
*
* @param key
* 键
* @param value
* 值
* @param cacheSeconds
* 超时时间,0为不超时
* @return
*/
public String setObject(String key, Object value, int cacheSeconds) {
String result = null;
Jedis jedis = null;
try {
jedis = getResource();
result = jedis.set(getBytesKey(key), toBytes(value));
if (cacheSeconds != 0) {
jedis.expire(key, cacheSeconds);
}
logger.debug("setObject {} = {}", key, value);
} catch (Exception e) {
logger.warn("setObject {} = {}", key, value, e);
} finally {
returnResource(jedis);
}
return result;
}
/**
* 获取List缓存
*
* @param key
* 键
* @return 值
*/
public List<String> getList(String key) {
List<String> value = null;
Jedis jedis = null;
try {
jedis = getResource();
if (jedis.exists(key)) {
value = jedis.lrange(key, 0, -1);
logger.debug("getList {} = {}", key, value);
}
} catch (Exception e) {
logger.warn("getList {} = {}", key, value, e);
} finally {
returnResource(jedis);
}
return value;
}
/**
* 获取List缓存
*
* @param key
* 键
* @return 值
*/
public List<Object> getObjectList(String key) {
List<Object> value = null;
Jedis jedis = null;
try {
jedis = getResource();
if (jedis.exists(getBytesKey(key))) {
List<byte[]> list = jedis.lrange(getBytesKey(key), 0, -1);
value = Lists.newArrayList();
for (byte[] bs : list) {
value.add(toObject(bs));
}
logger.debug("getObjectList {} = {}", key, value);
}
} catch (Exception e) {
logger.warn("getObjectList {} = {}", key, value, e);
} finally {
returnResource(jedis);
}
return value;
}
/**
* 设置List缓存
*
* @param key
* 键
* @param value
* 值
* @param cacheSeconds
* 超时时间,0为不超时
* @return
*/
public long setList(String key, List<String> value, int cacheSeconds) {
long result = 0;
Jedis jedis = null;
try {
jedis = getResource();
if (jedis.exists(key)) {
jedis.del(key);
}
result = jedis.rpush(key, (String[]) value.toArray());
if (cacheSeconds != 0) {
jedis.expire(key, cacheSeconds);
}
logger.debug("setList {} = {}", key, value);
} catch (Exception e) {
logger.warn("setList {} = {}", key, value, e);
} finally {
returnResource(jedis);
}
return result;
}
/**
* 设置List缓存
*
* @param key
* 键
* @param value
* 值
* @param cacheSeconds
* 超时时间,0为不超时
* @return
*/
public long setObjectList(String key, List<Object> value, int cacheSeconds) {
long result = 0;
Jedis jedis = null;
try {
jedis = getResource();
if (jedis.exists(getBytesKey(key))) {
jedis.del(key);
}
List<byte[]> list = Lists.newArrayList();
for (Object o : value) {
list.add(toBytes(o));
}
result = jedis.rpush(getBytesKey(key), (byte[][]) list.toArray());
if (cacheSeconds != 0) {
jedis.expire(key, cacheSeconds);
}
logger.debug("setObjectList {} = {}", key, value);
} catch (Exception e) {
logger.warn("setObjectList {} = {}", key, value, e);
} finally {
returnResource(jedis);
}
return result;
}
/**
* 向List缓存中添加值
*
* @param key
* 键
* @param value
* 值
* @return
*/
public long listAdd(String key, String... value) {
long result = 0;
Jedis jedis = null;
try {
jedis = getResource();
result = jedis.rpush(key, value);
logger.debug("listAdd {} = {}", key, value);
} catch (Exception e) {
logger.warn("listAdd {} = {}", key, value, e);
} finally {
returnResource(jedis);
}
return result;
}
/**
* 向List缓存中添加值
*
* @param key
* 键
* @param value
* 值
* @return
*/
public long listObjectAdd(String key, Object... value) {
long result = 0;
Jedis jedis = null;
try {
jedis = getResource();
List<byte[]> list = Lists.newArrayList();
for (Object o : value) {
list.add(toBytes(o));
}
result = jedis.rpush(getBytesKey(key), (byte[][]) list.toArray());
logger.debug("listObjectAdd {} = {}", key, value);
} catch (Exception e) {
logger.warn("listObjectAdd {} = {}", key, value, e);
} finally {
returnResource(jedis);
}
return result;
}
/**
* 获取缓存
*
* @param key
* 键
* @return 值
*/
public Set<String> getSet(String key) {
Set<String> value = null;
Jedis jedis = null;
try {
jedis = getResource();
if (jedis.exists(key)) {
value = jedis.smembers(key);
logger.debug("getSet {} = {}", key, value);
}
} catch (Exception e) {
logger.warn("getSet {} = {}", key, value, e);
} finally {
returnResource(jedis);
}
return value;
}
/**
* 获取缓存
*
* @param key
* 键
* @return 值
*/
public Set<Object> getObjectSet(String key) {
Set<Object> value = null;
Jedis jedis = null;
try {
jedis = getResource();
if (jedis.exists(getBytesKey(key))) {
value = Sets.newHashSet();
Set<byte[]> set = jedis.smembers(getBytesKey(key));
for (byte[] bs : set) {
value.add(toObject(bs));
}
logger.debug("getObjectSet {} = {}", key, value);
}
} catch (Exception e) {
logger.warn("getObjectSet {} = {}", key, value, e);
} finally {
returnResource(jedis);
}
return value;
}
/**
* 设置Set缓存
*
* @param key
* 键
* @param value
* 值
* @param cacheSeconds
* 超时时间,0为不超时
* @return
*/
public long setSet(String key, Set<String> value, int cacheSeconds) {
long result = 0;
Jedis jedis = null;
try {
jedis = getResource();
if (jedis.exists(key)) {
jedis.del(key);
}
result = jedis.sadd(key, (String[]) value.toArray());
if (cacheSeconds != 0) {
jedis.expire(key, cacheSeconds);
}
logger.debug("setSet {} = {}", key, value);
} catch (Exception e) {
logger.warn("setSet {} = {}", key, value, e);
} finally {
returnResource(jedis);
}
return result;
}
/**
* 设置Set缓存
*
* @param key
* 键
* @param value
* 值
* @param cacheSeconds
* 超时时间,0为不超时
* @return
*/
public long setObjectSet(String key, Set<Object> value, int cacheSeconds) {
long result = 0;
Jedis jedis = null;
try {
jedis = getResource();
if (jedis.exists(getBytesKey(key))) {
jedis.del(key);
}
Set<byte[]> set = Sets.newHashSet();
for (Object o : value) {
set.add(toBytes(o));
}
result = jedis.sadd(getBytesKey(key), (byte[][]) set.toArray());
if (cacheSeconds != 0) {
jedis.expire(key, cacheSeconds);
}
logger.debug("setObjectSet {} = {}", key, value);
} catch (Exception e) {
logger.warn("setObjectSet {} = {}", key, value, e);
} finally {
returnResource(jedis);
}
return result;
}
/**
* 向Set缓存中添加值
*
* @param key
* 键
* @param value
* 值
* @return
*/
public long setSetAdd(String key, String... value) {
long result = 0;
Jedis jedis = null;
try {
jedis = getResource();
result = jedis.sadd(key, value);
logger.debug("setSetAdd {} = {}", key, value);
} catch (Exception e) {
logger.warn("setSetAdd {} = {}", key, value, e);
} finally {
returnResource(jedis);
}
return result;
}
/**
* 向Set缓存中添加值
*
* @param key
* 键
* @param value
* 值
* @return
*/
public long setSetObjectAdd(String key, Object... value) {
long result = 0;
Jedis jedis = null;
try {
jedis = getResource();
Set<byte[]> set = Sets.newHashSet();
for (Object o : value) {
set.add(toBytes(o));
}
result = jedis.rpush(getBytesKey(key), (byte[][]) set.toArray());
logger.debug("setSetObjectAdd {} = {}", key, value);
} catch (Exception e) {
logger.warn("setSetObjectAdd {} = {}", key, value, e);
} finally {
returnResource(jedis);
}
return result;
}
/**
* 获取Map缓存
*
* @param key
* 键
* @return 值
*/
public Map<String, String> getMap(String key) {
Map<String, String> value = null;
Jedis jedis = null;
try {
jedis = getResource();
if (jedis.exists(key)) {
value = jedis.hgetAll(key);
logger.debug("getMap {} = {}", key, value);
}
} catch (Exception e) {
logger.warn("getMap {} = {}", key, value, e);
} finally {
returnResource(jedis);
}
return value;
}
/**
* 获取Map缓存
*
* @param key
* 键
* @return 值
*/
public Map<String, Object> getObjectMap(String key) {
Map<String, Object> value = null;
Jedis jedis = null;
try {
jedis = getResource();
if (jedis.exists(getBytesKey(key))) {
value = Maps.newHashMap();
Map<byte[], byte[]> map = jedis.hgetAll(getBytesKey(key));
for (Map.Entry<byte[], byte[]> e : map.entrySet()) {
value.put(StringUtils.toString(e.getKey()), toObject(e.getValue()));
}
logger.debug("getObjectMap {} = {}", key, value);
}
} catch (Exception e) {
logger.warn("getObjectMap {} = {}", key, value, e);
} finally {
returnResource(jedis);
}
return value;
}
/**
* 设置Map缓存
*
* @param key
* 键
* @param value
* 值
* @param cacheSeconds
* 超时时间,0为不超时
* @return
*/
public String setMap(String key, Map<String, String> value, int cacheSeconds) {
String result = null;
Jedis jedis = null;
try {
jedis = getResource();
if (jedis.exists(key)) {
jedis.del(key);
}
result = jedis.hmset(key, value);
if (cacheSeconds != 0) {
jedis.expire(key, cacheSeconds);
}
logger.debug("setMap {} = {}", key, value);
} catch (Exception e) {
logger.warn("setMap {} = {}", key, value, e);
} finally {
returnResource(jedis);
}
return result;
}
/**
* 设置Map缓存
*
* @param key
* 键
* @param value
* 值
* @param cacheSeconds
* 超时时间,0为不超时
* @return
*/
public String setObjectMap(String key, Map<String, Object> value, int cacheSeconds) {
String result = null;
Jedis jedis = null;
try {
jedis = getResource();
if (jedis.exists(getBytesKey(key))) {
jedis.del(key);
}
Map<byte[], byte[]> map = Maps.newHashMap();
for (Map.Entry<String, Object> e : value.entrySet()) {
map.put(getBytesKey(e.getKey()), toBytes(e.getValue()));
}
result = jedis.hmset(getBytesKey(key), (Map<byte[], byte[]>) map);
if (cacheSeconds != 0) {
jedis.expire(key, cacheSeconds);
}
logger.debug("setObjectMap {} = {}", key, value);
} catch (Exception e) {
logger.warn("setObjectMap {} = {}", key, value, e);
} finally {
returnResource(jedis);
}
return result;
}
/**
* 向Map缓存中添加值
*
* @param key
* 键
* @param value
* 值
* @return
*/
public String mapPut(String key, Map<String, String> value) {
String result = null;
Jedis jedis = null;
try {
jedis = getResource();
result = jedis.hmset(key, value);
logger.debug("mapPut {} = {}", key, value);
} catch (Exception e) {
logger.warn("mapPut {} = {}", key, value, e);
} finally {
returnResource(jedis);
}
return result;
}
/**
* 向Map缓存中添加值
*
* @param key
* 键
* @param value
* 值
* @return
*/
public String mapObjectPut(String key, Map<String, Object> value) {
String result = null;
Jedis jedis = null;
try {
jedis = getResource();
Map<byte[], byte[]> map = Maps.newHashMap();
for (Map.Entry<String, Object> e : value.entrySet()) {
map.put(getBytesKey(e.getKey()), toBytes(e.getValue()));
}
result = jedis.hmset(getBytesKey(key), (Map<byte[], byte[]>) map);
logger.debug("mapObjectPut {} = {}", key, value);
} catch (Exception e) {
logger.warn("mapObjectPut {} = {}", key, value, e);
} finally {
returnResource(jedis);
}
return result;
}
/**
* 移除Map缓存中的值
*
* @param key
* 键
* @param value
* 值
* @return
*/
public long mapRemove(String key, String mapKey) {
long result = 0;
Jedis jedis = null;
try {
jedis = getResource();
result = jedis.hdel(key, mapKey);
logger.debug("mapRemove {} {}", key, mapKey);
} catch (Exception e) {
logger.warn("mapRemove {} {}", key, mapKey, e);
} finally {
returnResource(jedis);
}
return result;
}
/**
* 移除Map缓存中的值
*
* @param key
* 键
* @param value
* 值
* @return
*/
public long mapObjectRemove(String key, String mapKey) {
long result = 0;
Jedis jedis = null;
try {
jedis = getResource();
result = jedis.hdel(getBytesKey(key), getBytesKey(mapKey));
logger.debug("mapObjectRemove {} {}", key, mapKey);
} catch (Exception e) {
logger.warn("mapObjectRemove {} {}", key, mapKey, e);
} finally {
returnResource(jedis);
}
return result;
}
/**
* 判断Map缓存中的Key是否存在
*
* @param key
* 键
* @param value
* 值
* @return
*/
public boolean mapExists(String key, String mapKey) {
boolean result = false;
Jedis jedis = null;
try {
jedis = getResource();
result = jedis.hexists(key, mapKey);
logger.debug("mapExists {} {}", key, mapKey);
} catch (Exception e) {
logger.warn("mapExists {} {}", key, mapKey, e);
} finally {
returnResource(jedis);
}
return result;
}
/**
* 判断Map缓存中的Key是否存在
*
* @param key
* 键
* @param value
* 值
* @return
*/
public boolean mapObjectExists(String key, String mapKey) {
boolean result = false;
Jedis jedis = null;
try {
jedis = getResource();
result = jedis.hexists(getBytesKey(key), getBytesKey(mapKey));
logger.debug("mapObjectExists {} {}", key, mapKey);
} catch (Exception e) {
logger.warn("mapObjectExists {} {}", key, mapKey, e);
} finally {
returnResource(jedis);
}
return result;
}
/**
* 删除缓存
*
* @param key
* 键
* @return
*/
public long del(String key) {
long result = 0;
Jedis jedis = null;
try {
jedis = getResource();
if (jedis.exists(key)) {
result = jedis.del(key);
logger.debug("del {}", key);
} else {
logger.debug("del {} not exists", key);
}
} catch (Exception e) {
logger.warn("del {}", key, e);
} finally {
returnResource(jedis);
}
return result;
}
/**
* 删除缓存
*
* @param key
* 键
* @return
*/
public long delObject(String key) {
long result = 0;
Jedis jedis = null;
try {
jedis = getResource();
if (jedis.exists(getBytesKey(key))) {
result = jedis.del(getBytesKey(key));
logger.debug("delObject {}", key);
} else {
logger.debug("delObject {} not exists", key);
}
} catch (Exception e) {
logger.warn("delObject {}", key, e);
} finally {
returnResource(jedis);
}
return result;
}
/**
* 缓存是否存在
*
* @param key
* 键
* @return
*/
public boolean exists(String key) {
boolean result = false;
Jedis jedis = null;
try {
jedis = getResource();
result = jedis.exists(key);
logger.debug("exists {}", key);
} catch (Exception e) {
logger.warn("exists {}", key, e);
} finally {
returnResource(jedis);
}
return result;
}
/**
* 缓存是否存在
*
* @param key
* 键
* @return
*/
public boolean existsObject(String key) {
boolean result = false;
Jedis jedis = null;
try {
jedis = getResource();
result = jedis.exists(getBytesKey(key));
logger.debug("existsObject {}", key);
} catch (Exception e) {
logger.warn("existsObject {}", key, e);
} finally {
returnResource(jedis);
}
return result;
}
/**
* 获取资源
*
* @return
* @throws JedisException
*/
public Jedis getResource() throws JedisException {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
// logger.debug("getResource.", jedis);
} catch (JedisException e) {
logger.warn("getResource.", e);
returnBrokenResource(jedis);
throw e;
}
return jedis;
}
/**
* 归还资源
*
* @param jedis
* @param isBroken
*/
public void returnBrokenResource(Jedis jedis) {
if (jedis != null) {
jedisPool.returnBrokenResource(jedis);
}
}
/**
* 释放资源
*
* @param jedis
* @param isBroken
*/
public void returnResource(Jedis jedis) {
if (jedis != null) {
jedisPool.returnResource(jedis);
}
}
/**
* 获取byte[]类型Key
*
* @param key
* @return
*/
public static byte[] getBytesKey(Object object) {
if (object instanceof String) {
return StringUtils.getBytes((String) object);
} else {
return ObjectUtils.serialize(object);
}
}
/**
* Object转换byte[]类型
*
* @param key
* @return
*/
public static byte[] toBytes(Object object) {
return ObjectUtils.serialize(object);
}
/**
* byte[]型转换Object
*
* @param key
* @return
*/
public static Object toObject(byte[] bytes) {
return ObjectUtils.unserialize(bytes);
}
}
JedisClusterClient 实现类:
/**
* redis 集群版连接客户端
* <p> @ClassName : JedisClusterClient </p>
* <p> @Description : TODO </p>
* @Author : HuaZai
* @ContactInformation : 1461522031@qq.com/huazai6789@aliyun.com
* @Date : 2018年1月19日 下午3:04:21
* @Version : V1.0.0
*
* @param
*/
public class JedisClusterClient implements JedisClient {
private Logger logger = LoggerFactory.getLogger(JedisClusterClient.class);
@Autowired
private JedisCluster jedisCluster ;
@Override
public String get(String key) {
String value = null;
try {
if (jedisCluster.exists(key)) {
value = jedisCluster.get(key);
value = StringUtils.isNotBlank(value) && !"nil".equalsIgnoreCase(value) ? value : null;
logger.debug("get {} = {}", key, value);
}
} catch (Exception e) {
logger.warn("get {} = {}", key, value, e);
} finally {
}
return value;
}
@Override
public Object getObject(String key) {
Object value = null;
try {
if (jedisCluster.exists(getBytesKey(key))) {
value = toObject(jedisCluster.get(getBytesKey(key)));
logger.debug("getObject {} = {}", key, value);
}
} catch (Exception e) {
logger.warn("getObject {} = {}", key, value, e);
} finally {
}
return value;
}
@Override
public String set(String key, String value, int cacheSeconds) {
String result = null;
try {
result = jedisCluster.set(key, value);
if (cacheSeconds != 0) {
jedisCluster.expire(key, cacheSeconds);
}
logger.debug("set {} = {}", key, value);
} catch (Exception e) {
logger.warn("set {} = {}", key, value, e);
} finally {
}
return result;
}
@Override
public String setObject(String key, Object value, int cacheSeconds) {
String result = null;
try {
result = jedisCluster.set(getBytesKey(key), toBytes(value));
if (cacheSeconds != 0) {
jedisCluster.expire(key, cacheSeconds);
}
logger.debug("setObject {} = {}", key, value);
} catch (Exception e) {
logger.warn("setObject {} = {}", key, value, e);
} finally {
}
return result;
}
@Override
public List<String> getList(String key) {
List<String> value = null;
try {
if (jedisCluster.exists(key)) {
value = jedisCluster.lrange(key, 0, -1);
logger.debug("getList {} = {}", key, value);
}
} catch (Exception e) {
logger.warn("getList {} = {}", key, value, e);
} finally {
}
return value;
}
@Override
public List<Object> getObjectList(String key) {
List<Object> value = null;
try {
if (jedisCluster.exists(getBytesKey(key))) {
List<byte[]> list = jedisCluster.lrange(getBytesKey(key), 0, -1);
value = Lists.newArrayList();
for (byte[] bs : list){
value.add(toObject(bs));
}
logger.debug("getObjectList {} = {}", key, value);
}
} catch (Exception e) {
logger.warn("getObjectList {} = {}", key, value, e);
} finally {
}
return value;
}
@Override
public long setList(String key, List<String> value, int cacheSeconds) {
long result = 0;
try {
if (jedisCluster.exists(key)) {
jedisCluster.del(key);
}
result = jedisCluster.rpush(key, (String[])value.toArray());
if (cacheSeconds != 0) {
jedisCluster.expire(key, cacheSeconds);
}
logger.debug("setList {} = {}", key, value);
} catch (Exception e) {
logger.warn("setList {} = {}", key, value, e);
} finally {
}
return result;
}
@Override
public long setObjectList(String key, List<Object> value, int cacheSeconds) {
long result = 0;
try {
if (jedisCluster.exists(getBytesKey(key))) {
jedisCluster.del(key);
}
List<byte[]> list = Lists.newArrayList();
for (Object o : value){
list.add(toBytes(o));
}
result = jedisCluster.rpush(getBytesKey(key), (byte[][])list.toArray());
if (cacheSeconds != 0) {
jedisCluster.expire(key, cacheSeconds);
}
logger.debug("setObjectList {} = {}", key, value);
} catch (Exception e) {
logger.warn("setObjectList {} = {}", key, value, e);
} finally {
}
return result;
}
@Override
public long listAdd(String key, String... value) {
long result = 0;
try {
result = jedisCluster.rpush(key, value);
logger.debug("listAdd {} = {}", key, value);
} catch (Exception e) {
logger.warn("listAdd {} = {}", key, value, e);
} finally {
}
return result;
}
@Override
public long listObjectAdd(String key, Object... value) {
long result = 0;
try {
List<byte[]> list = Lists.newArrayList();
for (Object o : value){
list.add(toBytes(o));
}
result = jedisCluster.rpush(getBytesKey(key), (byte[][])list.toArray());
logger.debug("listObjectAdd {} = {}", key, value);
} catch (Exception e) {
logger.warn("listObjectAdd {} = {}", key, value, e);
} finally {
}
return result;
}
@Override
public Set<String> getSet(String key) {
Set<String> value = null;
try {
if (jedisCluster.exists(key)) {
value = jedisCluster.smembers(key);
logger.debug("getSet {} = {}", key, value);
}
} catch (Exception e) {
logger.warn("getSet {} = {}", key, value, e);
} finally {
}
return value;
}
@Override
public Set<Object> getObjectSet(String key) {
Set<Object> value = null;
try {
if (jedisCluster.exists(getBytesKey(key))) {
value = Sets.newHashSet();
Set<byte[]> set = jedisCluster.smembers(getBytesKey(key));
for (byte[] bs : set){
value.add(toObject(bs));
}
logger.debug("getObjectSet {} = {}", key, value);
}
} catch (Exception e) {
logger.warn("getObjectSet {} = {}", key, value, e);
} finally {
}
return value;
}
@Override
public long setSet(String key, Set<String> value, int cacheSeconds) {
long result = 0;
try {
if (jedisCluster.exists(key)) {
jedisCluster.del(key);
}
result = jedisCluster.sadd(key, (String[])value.toArray());
if (cacheSeconds != 0) {
jedisCluster.expire(key, cacheSeconds);
}
logger.debug("setSet {} = {}", key, value);
} catch (Exception e) {
logger.warn("setSet {} = {}", key, value, e);
} finally {
}
return result;
}
@Override
public long setObjectSet(String key, Set<Object> value, int cacheSeconds) {
long result = 0;
try {
if (jedisCluster.exists(getBytesKey(key))) {
jedisCluster.del(key);
}
Set<byte[]> set = Sets.newHashSet();
for (Object o : value){
set.add(toBytes(o));
}
result = jedisCluster.sadd(getBytesKey(key), (byte[][])set.toArray());
if (cacheSeconds != 0) {
jedisCluster.expire(key, cacheSeconds);
}
logger.debug("setObjectSet {} = {}", key, value);
} catch (Exception e) {
logger.warn("setObjectSet {} = {}", key, value, e);
} finally {
}
return result;
}
@Override
public long setSetAdd(String key, String... value) {
long result = 0;
try {
result = jedisCluster.sadd(key, value);
logger.debug("setSetAdd {} = {}", key, value);
} catch (Exception e) {
logger.warn("setSetAdd {} = {}", key, value, e);
} finally {
}
return result;
}
@Override
public long setSetObjectAdd(String key, Object... value) {
long result = 0;
try {
Set<byte[]> set = Sets.newHashSet();
for (Object o : value){
set.add(toBytes(o));
}
result = jedisCluster.rpush(getBytesKey(key), (byte[][])set.toArray());
logger.debug("setSetObjectAdd {} = {}", key, value);
} catch (Exception e) {
logger.warn("setSetObjectAdd {} = {}", key, value, e);
} finally {
}
return result;
}
@Override
public Map<String, String> getMap(String key) {
Map<String, String> value = null;
try {
if (jedisCluster.exists(key)) {
value = jedisCluster.hgetAll(key);
logger.debug("getMap {} = {}", key, value);
}
} catch (Exception e) {
logger.warn("getMap {} = {}", key, value, e);
} finally {
}
return value;
}
@Override
public Map<String, Object> getObjectMap(String key) {
Map<String, Object> value = null;
try {
if (jedisCluster.exists(getBytesKey(key))) {
value = Maps.newHashMap();
Map<byte[], byte[]> map = jedisCluster.hgetAll(getBytesKey(key));
for (Map.Entry<byte[], byte[]> e : map.entrySet()){
value.put(StringUtils.toString(e.getKey()), toObject(e.getValue()));
}
logger.debug("getObjectMap {} = {}", key, value);
}
} catch (Exception e) {
logger.warn("getObjectMap {} = {}", key, value, e);
} finally {
}
return value;
}
@Override
public String setMap(String key, Map<String, String> value, int cacheSeconds) {
String result = null;
try {
if (jedisCluster.exists(key)) {
jedisCluster.del(key);
}
result = jedisCluster.hmset(key, value);
if (cacheSeconds != 0) {
jedisCluster.expire(key, cacheSeconds);
}
logger.debug("setMap {} = {}", key, value);
} catch (Exception e) {
logger.warn("setMap {} = {}", key, value, e);
} finally {
}
return result;
}
@Override
public String setObjectMap(String key, Map<String, Object> value, int cacheSeconds) {
String result = null;
try {
if (jedisCluster.exists(getBytesKey(key))) {
jedisCluster.del(key);
}
Map<byte[], byte[]> map = Maps.newHashMap();
for (Map.Entry<String, Object> e : value.entrySet()){
map.put(getBytesKey(e.getKey()), toBytes(e.getValue()));
}
result = jedisCluster.hmset(getBytesKey(key), (Map<byte[], byte[]>)map);
if (cacheSeconds != 0) {
jedisCluster.expire(key, cacheSeconds);
}
logger.debug("setObjectMap {} = {}", key, value);
} catch (Exception e) {
logger.warn("setObjectMap {} = {}", key, value, e);
} finally {
}
return result;
}
@Override
public String mapPut(String key, Map<String, String> value) {
String result = null;
try {
result = jedisCluster.hmset(key, value);
logger.debug("mapPut {} = {}", key, value);
} catch (Exception e) {
logger.warn("mapPut {} = {}", key, value, e);
} finally {
}
return result;
}
@Override
public String mapObjectPut(String key, Map<String, Object> value) {
String result = null;
try {
Map<byte[], byte[]> map = Maps.newHashMap();
for (Map.Entry<String, Object> e : value.entrySet()){
map.put(getBytesKey(e.getKey()), toBytes(e.getValue()));
}
result = jedisCluster.hmset(getBytesKey(key), (Map<byte[], byte[]>)map);
logger.debug("mapObjectPut {} = {}", key, value);
} catch (Exception e) {
logger.warn("mapObjectPut {} = {}", key, value, e);
} finally {
}
return result;
}
@Override
public long mapRemove(String key, String mapKey) {
long result = 0;
try {
result = jedisCluster.hdel(key, mapKey);
logger.debug("mapRemove {} {}", key, mapKey);
} catch (Exception e) {
logger.warn("mapRemove {} {}", key, mapKey, e);
} finally {
}
return result;
}
@Override
public long mapObjectRemove(String key, String mapKey) {
long result = 0;
try {
result = jedisCluster.hdel(getBytesKey(key), getBytesKey(mapKey));
logger.debug("mapObjectRemove {} {}", key, mapKey);
} catch (Exception e) {
logger.warn("mapObjectRemove {} {}", key, mapKey, e);
} finally {
}
return result;
}
@Override
public boolean mapExists(String key, String mapKey) {
boolean result = false;
try {
result = jedisCluster.hexists(key, mapKey);
logger.debug("mapExists {} {}", key, mapKey);
} catch (Exception e) {
logger.warn("mapExists {} {}", key, mapKey, e);
} finally {
}
return result;
}
@Override
public boolean mapObjectExists(String key, String mapKey) {
boolean result = false;
try {
result = jedisCluster.hexists(getBytesKey(key), getBytesKey(mapKey));
logger.debug("mapObjectExists {} {}", key, mapKey);
} catch (Exception e) {
logger.warn("mapObjectExists {} {}", key, mapKey, e);
} finally {
}
return result;
}
@Override
public long del(String key) {
long result = 0;
try {
if (jedisCluster.exists(key)){
result = jedisCluster.del(key);
logger.debug("del {}", key);
}else{
logger.debug("del {} not exists", key);
}
} catch (Exception e) {
logger.warn("del {}", key, e);
} finally {
}
return result;
}
@Override
public long delObject(String key) {
long result = 0;
try {
if (jedisCluster.exists(getBytesKey(key))){
result = jedisCluster.del(getBytesKey(key));
logger.debug("delObject {}", key);
}else{
logger.debug("delObject {} not exists", key);
}
} catch (Exception e) {
logger.warn("delObject {}", key, e);
} finally {
}
return result;
}
@Override
public boolean exists(String key) {
boolean result = false;
try {
result = jedisCluster.exists(key);
logger.debug("exists {}", key);
} catch (Exception e) {
logger.warn("exists {}", key, e);
} finally {
}
return result;
}
@Override
public boolean existsObject(String key) {
boolean result = false;
try {
result = jedisCluster.exists(getBytesKey(key));
logger.debug("existsObject {}", key);
} catch (Exception e) {
logger.warn("existsObject {}", key, e);
} finally {
}
return result;
}
/**
* 获取byte[]类型Key
* @param key
* @return
*/
public static byte[] getBytesKey(Object object){
if(object instanceof String){
return StringUtils.getBytes((String)object);
}else{
return ObjectUtils.serialize(object);
}
}
/**
* Object转换byte[]类型
* @param key
* @return
*/
public static byte[] toBytes(Object object){
return ObjectUtils.serialize(object);
}
/**
* byte[]型转换Object
* @param key
* @return
*/
public static Object toObject(byte[] bytes){
return ObjectUtils.unserialize(bytes);
}
}
jedis 工厂类:
/**
* jedis 集群工厂
* <p> @ClassName : JedisClusterFactory </p>
* <p> @Description : TODO </p>
* @Author : HuaZai
* @ContactInformation : 1461522031@qq.com/huazai6789@aliyun.com
* @Date : 2018年1月19日 下午3:13:05
* @Version : V1.0.0
*
* @param
*/
public class JedisClusterFactory implements FactoryBean<JedisCluster>,
InitializingBean {
//连接池参数 spring 注入
private GenericObjectPoolConfig genericObjectPoolConfig;
//
private JedisCluster jedisCluster;
private int connectionTimeout = 2000;
private int soTimeout = 3000;
private int maxRedirections = 5;
//redis结点列表 spring注入
private Set<String> jedisClusterNodes;
@Override
public void afterPropertiesSet() throws Exception {
//判断地址是否为空
if(jedisClusterNodes == null || jedisClusterNodes.size() == 0){
throw new NullPointerException("jedisClusterNodes is null.");
}
//构造结点
Set<HostAndPort> haps = new HashSet<HostAndPort>();
for(String node:jedisClusterNodes){
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, soTimeout, maxRedirections, genericObjectPoolConfig);
}
@Override
public JedisCluster getObject() throws Exception {
return jedisCluster;
}
@Override
public Class<?> getObjectType() {
return (this.jedisCluster != null ? this.jedisCluster.getClass()
: JedisCluster.class);
}
@Override
public boolean isSingleton() {
// TODO Auto-generated method stub
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;
}
}
Redis 实现类:
/**
* Redis 操作实现类
* <p> @ClassName : RedisOperate </p>
* <p> @Description : TODO </p>
* @Author : HuaZai
* @ContactInformation : 1461522031@qq.com/huazai6789@aliyun.com
* @Date : 2018年1月19日 下午3:16:08
* @Version : V1.0.0
*
* @param
*/
public class RedisOperate implements JedisClient {
JedisClient jedisClient;
public JedisClient getJedisClient() {
return jedisClient;
}
public void setJedisClient(JedisClient jedisClient) {
this.jedisClient = jedisClient;
}
@Override
public String get(String key) {
return jedisClient.get(key);
}
@Override
public Object getObject(String key) {
return jedisClient.getObject(key);
}
@Override
public String set(String key, String value, int cacheSeconds) {
return jedisClient.set(key, value, cacheSeconds);
}
@Override
public String setObject(String key, Object value, int cacheSeconds) {
return jedisClient.setObject(key, value, cacheSeconds);
}
@Override
public List<String> getList(String key) {
return jedisClient.getList(key);
}
@Override
public List<Object> getObjectList(String key) {
return jedisClient.getObjectList(key);
}
@Override
public long setList(String key, List<String> value, int cacheSeconds) {
return jedisClient.setList(key, value, cacheSeconds);
}
@Override
public long setObjectList(String key, List<Object> value, int cacheSeconds) {
return jedisClient.setObjectList(key, value, cacheSeconds);
}
@Override
public long listAdd(String key, String... value) {
return jedisClient.listAdd(key, value);
}
@Override
public long listObjectAdd(String key, Object... value) {
return jedisClient.listObjectAdd(key, value);
}
@Override
public Set<String> getSet(String key) {
return jedisClient.getSet(key);
}
@Override
public Set<Object> getObjectSet(String key) {
return jedisClient.getObjectSet(key);
}
@Override
public long setSet(String key, Set<String> value, int cacheSeconds) {
return jedisClient.setSet(key, value, cacheSeconds);
}
@Override
public long setObjectSet(String key, Set<Object> value, int cacheSeconds) {
return jedisClient.setObjectSet(key, value, cacheSeconds);
}
@Override
public long setSetAdd(String key, String... value) {
return jedisClient.setSetAdd(key, value);
}
@Override
public long setSetObjectAdd(String key, Object... value) {
return jedisClient.setSetObjectAdd(key, value);
}
@Override
public Map<String, String> getMap(String key) {
return jedisClient.getMap(key);
}
@Override
public Map<String, Object> getObjectMap(String key) {
return jedisClient.getObjectMap(key);
}
@Override
public String setMap(String key, Map<String, String> value, int cacheSeconds) {
return jedisClient.setMap(key, value, cacheSeconds);
}
@Override
public String setObjectMap(String key, Map<String, Object> value,
int cacheSeconds) {
// TODO Auto-generated method stub
return jedisClient.setObjectMap(key, value, cacheSeconds);
}
@Override
public String mapPut(String key, Map<String, String> value) {
// TODO Auto-generated method stub
return jedisClient.mapPut(key, value);
}
@Override
public String mapObjectPut(String key, Map<String, Object> value) {
// TODO Auto-generated method stub
return jedisClient.mapObjectPut(key, value);
}
@Override
public long mapRemove(String key, String mapKey) {
// TODO Auto-generated method stub
return jedisClient.mapRemove(key, mapKey);
}
@Override
public long mapObjectRemove(String key, String mapKey) {
return jedisClient.mapObjectRemove(key, mapKey);
}
@Override
public boolean mapExists(String key, String mapKey) {
return jedisClient.mapExists(key, mapKey);
}
@Override
public boolean mapObjectExists(String key, String mapKey) {
return jedisClient.mapObjectExists(key, mapKey);
}
@Override
public long del(String key) {
return jedisClient.del(key);
}
@Override
public long delObject(String key) {
return jedisClient.delObject(key);
}
@Override
public boolean exists(String key) {
return jedisClient.exists(key);
}
@Override
public boolean existsObject(String key) {
return jedisClient.existsObject(key);
}
}
jar包下载:http://download.csdn.net/download/hello_world_qwp/10214265