这里使用的是ShardedJedisPool,而不是RedisTemplate

1、配置文件

<?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:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"
default-autowire="byName"> <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxTotal" value="${redis.pool.maxTotal}" />
<property name="maxWaitMillis" value="${redis.pool.maxWaitMillis}" />
<property name="maxIdle" value="${redis.pool.maxIdle}" />
<property name="testOnBorrow" value="${redis.pool.testOnBorrow}" />
</bean>
<bean id="shardedJedisPool" class="redis.clients.jedis.ShardedJedisPool" scope="singleton">
<constructor-arg index="0" ref="jedisPoolConfig" />
<constructor-arg index="1">
<list>
<bean name="slave" class="redis.clients.jedis.JedisShardInfo">
<constructor-arg index="0" value="${redis.slave.ip}" />
<constructor-arg index="1" value="${redis.slave.port}" />
</bean>
<bean name="master" class="redis.clients.jedis.JedisShardInfo">
<constructor-arg index="0" value="${redis.master.ip}" />
<constructor-arg index="1" value="${redis.master.port}"/>
</bean>
</list>
</constructor-arg>
</bean>
<bean id="jedisConnectionFactory"
class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="hostName" value="${redis.master.ip}" />
<property name="port" value="${redis.master.port}" />
<property name="poolConfig" ref="jedisPoolConfig" />
</bean>
<!-- spring session 配置 -->
<bean id="redisHttpSessionConfiguration" class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration">
<property name="maxInactiveIntervalInSeconds" value="1800"/>
<property name="redisNamespace" value="ianbase" />
</bean>
<!--spring session 监听器-->
<!-- 让Spring Session不再执行config命令 -->
<util:constant static-field="org.springframework.session.data.redis.config.ConfigureRedisAction.NO_OP"/>
</beans>

2、序列化工具

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <p>
* Title:对象序列化和反序列化。
*/
public class SerializeUtil { private static Logger LOG = LoggerFactory.getLogger(SerializeUtil.class);
/**
* 序列化
*
* @param object
* @return byte[]
*/
public static byte[] serialize(Object object) {
ObjectOutputStream oos = null;
ByteArrayOutputStream baos = null;
if(object==null){
return null;
}
try {
// 序列化
baos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(baos);
oos.writeObject(object);
byte[] bytes = baos.toByteArray();
return bytes;
} catch (Exception e) {
LOG.error("serialize error",e);
} finally {
try {
if (oos != null) {
oos.close();
}
if (baos != null) {
baos.close();
}
} catch (Exception e2) {
LOG.error("serialize close error",e2);
}
}
return null;
}
/**
* 序列化
*
* @param byte[]
* @return object
*/
public static Object deserialize(byte[] bytes) {
if(bytes==null){
return null;
}
ByteArrayInputStream bais = null;
try {
// 反序列化
bais = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bais);
return ois.readObject();
} catch (Exception e) {
LOG.error("unserialize error",e);
}
return null;
} }

3、RedisClient

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import SerializeUtil; import redis.clients.jedis.Jedis;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPipeline;
import redis.clients.jedis.ShardedJedisPool; import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set; /**
* redis操作工具类
*/
@SuppressWarnings("unchecked")
@Component
public class RedisClient { private static final Logger LOG = LoggerFactory.getLogger(ShardRedisClient.class);
@Autowired
private ShardedJedisPool shardedJedisPool; /**
* 字符集
*/
private final Charset charset = Charset.forName("UTF-8"); public String deserialize(byte[] bytes) {
return (bytes == null ? null : new String(bytes, charset));
} public byte[] serialize(String string) {
return (string == null ? null : string.getBytes(charset));
} /**
* 设置单个值
*
* @param key
* @param value
* @return
*/
public boolean set(String key, String value) {
boolean flag = false;
ShardedJedis shardedJedis = shardedJedisPool.getResource();
try {
shardedJedis.set(key, value);
flag=true;
} catch (Exception e) {
LOG.error("set error", e);
} finally {
if(shardedJedis!=null){
shardedJedis.close();
}
}
return flag;
}
/**
* 批量设置设置
*
* @param key
* @param value
* @return
*/
public boolean setList(String key, String value) {
boolean flag = false;
ShardedJedis shardedJedis = shardedJedisPool.getResource();
try {
ShardedJedisPipeline shardedJedisPipeline=shardedJedis.pipelined();
shardedJedisPipeline.set(key, value);
shardedJedisPipeline.sync();
flag=true;
} catch (Exception e) {
LOG.error("set error", e);
} finally {
if(shardedJedis!=null){
shardedJedis.close();
}
}
return flag;
}
/**
* 设置单个值,并且设置过期时间
*
* @param key
* @param value
* @param second
* @return
*/
public boolean set(String key, String value, int second) {
ShardedJedis shardedJedis = null;
try {
shardedJedis = shardedJedisPool.getResource();
shardedJedis.setex(key, second, value);
return true;
} catch (Exception ex) {
LOG.error("set error.", ex);
} finally {
if(shardedJedis!=null){
shardedJedis.close();
} }
return false;
}
/**
* 删除所有匹配的key
*
* @param prefixKey
* @return
*/
public boolean delKesByPrefix(String prefixKey) {
ShardedJedis jedis = null;
Set<String> setResult = new HashSet<String>();
try {
jedis = shardedJedisPool.getResource();
Iterator<Jedis> jedisIterator = jedis.getAllShards().iterator();
while(jedisIterator.hasNext()){
setResult = jedisIterator.next().keys(prefixKey+"*");
}
Iterator<String> it=setResult.iterator();
while(it.hasNext()){
String key=it.next();
jedis.del(key);
}
return true;
} catch (Exception e) {
LOG.error("getByPrefix error", e);
}finally {
if(jedis!=null){
jedis.close();
}
}
return false;
}
/**
* 获取单个值
*
* @param key
* @return
*/
public String get(String key) {
String result = null;
ShardedJedis shardedJedis = shardedJedisPool.getResource();
if (shardedJedis == null) {
return result;
}
try {
result = shardedJedis.get(key);
} catch (Exception e) {
LOG.error("redis get error", e);
} finally {
if(shardedJedis!=null){
shardedJedis.close();
}
}
return result;
}
/**
* 删除HashSet对象
*
* @param key
* 键值
* @param field
* 属性
* @return 删除的记录数
*/
public long del(String key) {
ShardedJedis shardedJedis = null;
long count = 0;
try {
shardedJedis = shardedJedisPool.getResource();
count = shardedJedis.del(key);
} catch (Exception ex) {
LOG.error("hdel error.", ex); } finally {
if(shardedJedis!=null){
shardedJedis.close();
}
}
return count;
}
/**
* 设置一个key的过期时间(单位:秒)
*
* @param key
* key值
* @param seconds
* 多少秒后过期
* @return 1:设置了过期时间, 0:没有设置过期时间/不能设置过期时间
*/
public long expire(String key, int seconds) {
if (key == null || key.equals("")) {
return 0;
}
ShardedJedis shardedJedis = null;
try {
shardedJedis = shardedJedisPool.getResource();
return shardedJedis.expire(key, seconds);
} catch (Exception ex) {
LOG.error("EXPIRE error[key=" + key + " seconds=" + seconds + "]" + ex.getMessage(), ex);
} finally {
if(shardedJedis!=null){
shardedJedis.close();
}
}
return 0;
}
/**
* 设置HashSet对象
*
* @param key
* 键值
* @param field
* 属性
* @param value
* Json String or String value
* @return
*/
public boolean hset( String key,String field, String value) {
if (value == null)
return false;
ShardedJedis shardedJedis = null;
try {
shardedJedis = shardedJedisPool.getResource();
shardedJedis.hset(key, field, value);
return true;
} catch (Exception ex) {
LOG.error("hset error.", ex);
} finally {
if(shardedJedis!=null){
shardedJedis.close();
}
}
return false;
}
/**
* 设置HashSet对象
*
* @param key
* 键值
* @param field
* 属性
* @param value
* Json String or String value
* @return
*/
public boolean hmset(String key, Map<String ,String> map ) {
if (map == null)
return false;
ShardedJedis shardedJedis = null;
try {
shardedJedis = shardedJedisPool.getResource();
shardedJedis.hmset(key, map);
return true;
} catch (Exception ex) {
LOG.error("hmset error.", ex);
} finally {
if(shardedJedis!=null){
shardedJedis.close();
}
}
return false;
}
/**
* 设置HashSet对象
*
* @param key
* 键值
* @param field
* 属性
* @param value
* Json String or String value
* @return
*/
public boolean hmsetObject(String key, Map<String ,Object> map ) {
if (map == null)
return false;
ShardedJedis shardedJedis = null;
try {
shardedJedis = shardedJedisPool.getResource();
final Map<byte[], byte[]> hashes = new LinkedHashMap<byte[], byte[]>(map.size()); for (Map.Entry<String, Object> entry : map.entrySet()) {
hashes.put(serialize(entry.getKey()), SerializeUtil.serialize(entry.getValue()));
}
shardedJedis.hmset(serialize(key), hashes);
return true;
} catch (Exception ex) {
LOG.error("hmset error.", ex);
} finally {
if(shardedJedis!=null){
shardedJedis.close();
}
}
return false;
} /**
* 设置HashSet对象
*
* @param key
* 键值
* @param field
* 属性
* @param value
* Json String or String value
* @return
*/
public <T> boolean hmsetObjectClass(String key, Map<String ,T> map) {
if (map == null)
return false;
ShardedJedis shardedJedis = null;
try {
shardedJedis = shardedJedisPool.getResource();
final Map<byte[], byte[]> hashes = new LinkedHashMap<byte[], byte[]>(map.size()); for (Map.Entry<String, T> entry : map.entrySet()) {
hashes.put(serialize(entry.getKey()), SerializeUtil.serialize(entry.getValue()));
}
shardedJedis.hmset(serialize(key), hashes);
return true;
} catch (Exception ex) {
LOG.error("hmset error.", ex);
} finally {
if(shardedJedis!=null){
shardedJedis.close();
}
}
return false;
} /**
* 设置HashSet对象 ,并且设置过期时间
*
* @param key
* 键值
* @param map
*
* @param seconds
* 过期时间,单位秒。
* @return
*/
public boolean hmset(String key, Map<String ,String> map,int seconds ) {
if(this.hmset(key, map)){
return this.expire(key, seconds)==1;
}
return false;
} /**
* 获得HashSet对象
*
* @param key
* 键值
* @param field
* 属性
* @return Json String or String value
*/
public String hget(String key, String field) {
ShardedJedis shardedJedis = null;
try {
shardedJedis = shardedJedisPool.getResource();
return shardedJedis.hget(key, field);
} catch (Exception ex) {
LOG.error("hget error.", ex); } finally {
if(shardedJedis!=null){
shardedJedis.close();
}
}
return null;
}
/**
* 获得HashSet对象
*
* @param key
* 键值
* @param field
* 属性
* @return Json String or String value
*/
public Object hgetObject(String key, String field) {
ShardedJedis shardedJedis = null;
try {
shardedJedis = shardedJedisPool.getResource();
byte[] value=shardedJedis.hget(serialize(key), serialize(field));
return SerializeUtil.deserialize(value);
} catch (Exception ex) {
LOG.error("hget error.", ex); } finally {
if(shardedJedis!=null){
shardedJedis.close();
}
}
return null;
}
/**
* 获得HashSet对象
*
* @param key
* 键值
* @return Json String or String value
*/
public Map<String,Object> hgetMap(String key) {
ShardedJedis shardedJedis = null;
try {
shardedJedis = shardedJedisPool.getResource();
Map<byte[], byte[]> entries =shardedJedis.hgetAll(serialize(key));
Map<String,Object> map = new LinkedHashMap<String,Object>(entries.size()); for (Map.Entry<byte[], byte[]> entry : entries.entrySet()) {
map.put(deserialize(entry.getKey()), SerializeUtil.deserialize(entry.getValue()));
}
return map;
} catch (Exception ex) {
LOG.error("hgetAll error.", ex); } finally {
if(shardedJedis!=null){
shardedJedis.close();
}
}
return null;
} /**
* 获得缓存的Map,指定class
*
* @param key
* @return
*/
public <T> Map<String, T> hgetMapClass(Class<T> t,String key) {
ShardedJedis shardedJedis = null;
try {
shardedJedis = shardedJedisPool.getResource();
Map<byte[], byte[]> entries =shardedJedis.hgetAll(serialize(key));
Map map = new LinkedHashMap<String,Object>(entries.size()); for (Map.Entry<byte[], byte[]> entry : entries.entrySet()) {
map.put(deserialize(entry.getKey()), t.cast(SerializeUtil.deserialize(entry.getValue())));
}
return map;
} catch (Exception ex) {
LOG.error("hgetAll error.", ex);
} finally {
if(shardedJedis!=null){
shardedJedis.close();
}
}
return null;
}
/**
* 删除HashSet对象
*
* @param key
* 键值
* @param field
* 属性值
* @return 删除的记录数
*/
public long hdel(String key,String field) {
ShardedJedis shardedJedis = null;
long count = 0;
try {
shardedJedis = shardedJedisPool.getResource();
count = shardedJedis.hdel(key,field);
} catch (Exception ex) {
LOG.error("hdel error.", ex); } finally {
if(shardedJedis!=null){
shardedJedis.close();
}
}
return count;
} /**
* 删除HashSet对象
*
* @param key
* 键值
* @param field
* 属性
* @return 删除的记录数
*/
public long hdel(String key, String... field) {
ShardedJedis shardedJedis = null;
long count = 0;
try {
shardedJedis = shardedJedisPool.getResource();
count = shardedJedis.hdel(key,field);
} catch (Exception ex) {
LOG.error("hdel error.", ex); } finally {
if(shardedJedis!=null){
shardedJedis.close();
}
}
return count;
} /**
* 判断key是否存在
*
* @param key
* 键值
* @param field
* 属性
* @return
*/
public boolean hexists(String key, String field) {
ShardedJedis shardedJedis = null;
boolean isExist = false;
try {
shardedJedis = shardedJedisPool.getResource();
isExist = shardedJedis.hexists(key,field);
} catch (Exception ex) {
LOG.error("hexists error.", ex); } finally {
if(shardedJedis!=null){
shardedJedis.close();
}
}
return isExist;
} /**
* 判断key是否存在
*
* @param key
* 键值
* @return
*/
public boolean exists(String key) {
ShardedJedis shardedJedis = null;
boolean isExist = false;
try {
shardedJedis = shardedJedisPool.getResource();
isExist = shardedJedis.exists(key);
} catch (Exception ex) {
LOG.error("hexists error.", ex); } finally {
if(shardedJedis!=null){
shardedJedis.close();
}
}
return isExist;
} /**
* 返回 key 指定的哈希集中所有字段的value值
*
* @param key
* @return
*/ public List<String> hvals(String key) {
ShardedJedis shardedJedis = null;
List<String> retList = null;
try {
shardedJedis = shardedJedisPool.getResource();
retList = shardedJedis.hvals(key);
} catch (Exception ex) {
LOG.error("hvals error.", ex); } finally {
if(shardedJedis!=null){
shardedJedis.close();
}
}
return retList;
}
/**
* 返回 key 指定的哈希集中所有字段的value值
*
* @param key
* @return
*/ public <T> List<T> hvalsObject(String key) {
ShardedJedis shardedJedis = null;
List<Object> retList = new ArrayList<Object>();
try {
shardedJedis = shardedJedisPool.getResource();
Collection<byte[]> byteList=shardedJedis.hvals(serialize(key));
Iterator<byte[]> it=byteList.iterator();
while(it.hasNext()){
retList.add(SerializeUtil.deserialize(it.next()));
}
} catch (Exception ex) {
LOG.error("hvals error.", ex); } finally {
if(shardedJedis!=null){
shardedJedis.close();
}
}
return (List<T>)retList;
} /**
* 返回 key 指定的哈希集中所有字段的field值
*
* @param key
* @return
*/ public Set<String> hkeys(String key) {
ShardedJedis shardedJedis = null;
Set<String> retList = null;
try {
shardedJedis = shardedJedisPool.getResource();
retList = shardedJedis.hkeys(key);
} catch (Exception ex) {
LOG.error("hkeys error.", ex); } finally {
if(shardedJedis!=null){
shardedJedis.close();
}
}
return retList;
} /**
* 返回 key 指定的哈希field值总数
*
* @param key
* @return
*/
public long hlen(String key) {
ShardedJedis shardedJedis = null;
long retList = 0;
try {
shardedJedis = shardedJedisPool.getResource();
retList = shardedJedis.hlen(key);
} catch (Exception ex) {
LOG.error("hkeys error.", ex); } finally {
if(shardedJedis!=null){
shardedJedis.close();
}
}
return retList;
} /**
* 设置排序集合
*
* @param key
* @param score
* @param value
* @return
*/
public boolean setSortedSet(String key, long score, String value) {
ShardedJedis shardedJedis = null;
try {
shardedJedis = shardedJedisPool.getResource();
shardedJedis.zadd(key, score, value);
return true;
} catch (Exception ex) {
LOG.error("setSortedSet error.", ex); } finally {
if(shardedJedis!=null){
shardedJedis.close();
}
}
return false;
} /**
* 获得排序集合
*
* @param key
* @param startScore
* @param endScore
* @param orderByDesc
* @return
*/
public Set<String> getSoredSet(String key, long startScore, long endScore, boolean orderByDesc) {
ShardedJedis shardedJedis = null;
try {
shardedJedis = shardedJedisPool.getResource();
if (orderByDesc) {
return shardedJedis.zrevrangeByScore(key, endScore, startScore);
} else {
return shardedJedis.zrangeByScore(key, startScore, endScore);
}
} catch (Exception ex) {
LOG.error("getSoredSet error.", ex); } finally {
if(shardedJedis!=null){
shardedJedis.close();
}
}
return null;
} /**
* 计算排序长度
*
* @param key
* @param startScore
* @param endScore
* @return
*/
public long zcount(String key, long startScore, long endScore) {
ShardedJedis shardedJedis = null;
try {
shardedJedis = shardedJedisPool.getResource();
Long count = shardedJedis.zcount(key, startScore, endScore);
return count == null ? 0L : count;
} catch (Exception ex) {
LOG.error("zcount error.", ex); } finally {
if(shardedJedis!=null){
shardedJedis.close();
}
}
return 0L;
} /**
* 删除排序集合
*
* @param key
* @param value
* @return
*/
public boolean zrem(String key, String value) {
ShardedJedis shardedJedis = null;
try {
shardedJedis = shardedJedisPool.getResource();
long count = shardedJedis.zrem(key, value);
return count > 0;
} catch (Exception ex) {
LOG.error("zrem error.", ex); } finally {
if(shardedJedis!=null){
shardedJedis.close();
}
}
return false;
} /**
* 获得排序集合
*
* @param key
* @param startRange
* @param endRange
* @param orderByDesc
* @return
*/
public Set<String> zrange(String key, int startRange, int endRange, boolean orderByDesc) {
ShardedJedis shardedJedis = null;
try {
shardedJedis = shardedJedisPool.getResource();
if (orderByDesc) {
return shardedJedis.zrevrange(key, startRange, endRange);
} else {
return shardedJedis.zrange(key, startRange, endRange);
}
} catch (Exception ex) {
LOG.error("zrange error.", ex); } finally {
if(shardedJedis!=null){
shardedJedis.close();
}
}
return null;
} /**
* 获得排序打分
*
* @param key
* @return
*/
public Double zscore(String key, String member) {
ShardedJedis shardedJedis = null;
try {
shardedJedis = shardedJedisPool.getResource();
return shardedJedis.zscore(key, member);
} catch (Exception ex) {
LOG.error("zscore error.", ex); } finally {
if(shardedJedis!=null){
shardedJedis.close();
}
}
return null;
}
/**
* 从list中删除value 默认count 1
*
* @param key
* @param values
* 值list
* @return
*/
public int lrem(String key, List<String> values) {
return lrem(key, 1, values);
} /**
* 从list中删除value
*
* @param key
* @param count
* @param values
* 值list
* @return
*/
public int lrem(String key, long count, List<String> values) {
int result = 0;
if (values != null && values.size() > 0) {
for (String value : values) {
if (lrem(key, count, value)) {
result++;
}
}
}
return result;
} /**
* 从list中删除value
*
* @param key
* @param count
* 要删除个数
* @param value
* @return
*/
public boolean lrem(String key, long count, String value) {
ShardedJedis shardedJedis = null;
try {
shardedJedis = shardedJedisPool.getResource();
shardedJedis.lrem(key, count, value);
return true;
} catch (Exception ex) {
LOG.error("lrem error.", ex); } finally {
if(shardedJedis!=null){
shardedJedis.close();
}
}
return false;
} /**
* 截取List
*
* @param key
* @param start
* 起始位置
* @param end
* 结束位置
* @return
*/
public List<String> lrange(String key, long start, long end) {
if (key == null || key.equals("")) {
return null;
}
ShardedJedis shardedJedis = null;
try {
shardedJedis = shardedJedisPool.getResource();
return shardedJedis.lrange(key, start, end);
} catch (Exception ex) {
LOG.error("lrange 出错[key=" + key + " start=" + start + " end=" + end + "]" + ex.getMessage(), ex); } finally {
if(shardedJedis!=null){
shardedJedis.close();
}
}
return null;
} /**
* 检查List长度
*
* @param key
* @return
*/
public long llen(String key) {
if (key == null) {
return 0;
}
ShardedJedis shardedJedis = null;
try {
shardedJedis = shardedJedisPool.getResource();
return shardedJedis.llen(key);
} catch (Exception ex) {
LOG.error("llen error.", ex); } finally {
if(shardedJedis!=null){
shardedJedis.close();
}
}
return 0;
} /**
* 添加到List中(同时设置过期时间)
*
* @param key
* key值
* @param seconds
* 过期时间 单位s
* @param value
* @return
*/
public boolean lpush(String key, int seconds, String... value) {
boolean result = lpush(key, value);
if (result) {
long i = expire(key, seconds);
return i == 1;
}
return false;
} /**
* 添加到List
*
* @param key
* @param value
* @return
*/
public boolean lpush(String key, String... value) {
if (key == null || value == null) {
return false;
}
ShardedJedis shardedJedis = null;
try {
shardedJedis = shardedJedisPool.getResource();
shardedJedis.lpush(key, value);
return true;
} catch (Exception ex) {
LOG.error("lpush error.", ex); } finally {
if(shardedJedis!=null){
shardedJedis.close();
}
}
return false;
} /**
* 添加到List(只新增)
*
* @param key
* @param value
* @return
*/
public boolean lpush(String key, List<String> list) {
if (key == null || list == null || list.size() == 0) {
return false;
}
for (String value : list) {
lpush(key, value);
}
return true;
}
/**
* 截断一个List
*
* @param key
* 列表key
* @param start
* 开始位置 从0开始
* @param end
* 结束位置
* @return 状态码
*/
public String ltrim(String key, long start, long end) {
if (key == null || key.equals("")) {
return "-";
}
ShardedJedis shardedJedis = null;
try {
shardedJedis = shardedJedisPool.getResource();
return shardedJedis.ltrim(key, start, end);
} catch (Exception ex) {
LOG.error("ltrim 出错[key=" + key + " start=" + start + " end=" + end + "]" + ex.getMessage(), ex); } finally {
if(shardedJedis!=null){
shardedJedis.close();
}
}
return "-";
} /**
* 检查Set长度
*
* @param key
* @return
*/
public long scard(String key) {
if (key == null) {
return 0;
}
ShardedJedis shardedJedis = null;
try {
shardedJedis = shardedJedisPool.getResource();
return shardedJedis.scard(key);
} catch (Exception ex) {
LOG.error("scard error.", ex); } finally {
if(shardedJedis!=null){
shardedJedis.close();
}
}
return 0;
} /**
* 添加到Set中(同时设置过期时间)
*
* @param key
* key值
* @param seconds
* 过期时间 单位s
* @param value
* @return 成功true
*/
public boolean sadd(String key, int seconds, String... value) {
boolean result = sadd(key, value);
if (result) {
long i = expire(key, seconds);
return i == 1;
}
return false;
} /**
* 添加到Set中
*
* @param key
* @param value
* @return
*/
public boolean sadd(String key, String... value) {
if (key == null || value == null) {
return false;
}
ShardedJedis shardedJedis = null;
try {
shardedJedis = shardedJedisPool.getResource();
shardedJedis.sadd(key, value);
return true;
} catch (Exception ex) {
LOG.error("setList error.", ex); } finally {
if(shardedJedis!=null){
shardedJedis.close();
}
}
return false;
}
/**
* 添加到Set中
*
* @param key
* @param value
* @return
*/
public boolean saddObject(String key, Object... values) {
if (key == null || values == null) {
return false;
}
int length=values.length;
byte[][] array=new byte[length][]; ShardedJedis shardedJedis = null;
try {
shardedJedis = shardedJedisPool.getResource();
int i = 0;
for(Object value : values){
array[i++]=SerializeUtil.serialize(value);
}
shardedJedis.sadd(serialize(key), array);
return true;
} catch (Exception ex) {
LOG.error("setList error.", ex); } finally {
if(shardedJedis!=null){
shardedJedis.close();
}
}
return false;
} /**
* @param key
* @param value
* @return 判断值是否包含在set中
*/
public boolean sismember(String key, String value) {
if (key == null || value == null) {
return false;
}
ShardedJedis shardedJedis = null;
try {
shardedJedis = shardedJedisPool.getResource();
return shardedJedis.sismember(key, value);
} catch (Exception ex) {
LOG.error("sismember error.", ex); } finally {
if(shardedJedis!=null){
shardedJedis.close();
}
}
return false;
} /**
* 获取Set
*
* @param key
* @return
*/
public Set<String> smembers(String key) {
ShardedJedis shardedJedis = null;
try {
shardedJedis = shardedJedisPool.getResource();
return shardedJedis.smembers(key);
} catch (Exception ex) {
LOG.error("smembers error.", ex); } finally {
if(shardedJedis!=null){
shardedJedis.close();
}
}
return null;
}
/**
* 获取Set
*
* @param key
* @return
*/
public List<Object> smembersObjct(String key) {
List<Object> list = new ArrayList<Object>();
Set<byte[]> set = smembersByte(key);
Iterator<byte[]> it = set.iterator();
while (it.hasNext()) {
list.add(SerializeUtil.deserialize(it.next()));
}
return list; }
/**
* 获取Set
*
* @param key
* @return
*/
public Set<byte[]> smembersByte(String key) {
ShardedJedis shardedJedis = null;
try {
shardedJedis = shardedJedisPool.getResource();
return shardedJedis.smembers(key.getBytes(charset));
} catch (Exception ex) {
LOG.error("smembers error.", ex); } finally {
if(shardedJedis!=null){
shardedJedis.close();
}
}
return null;
} /**
* 从set中删除value
*
* @param key
* @return
*/
public boolean srem(String key, String... value) {
ShardedJedis shardedJedis = null;
try {
shardedJedis = shardedJedisPool.getResource();
shardedJedis.srem(key, value);
return true;
} catch (Exception ex) {
LOG.error("getList error.", ex); } finally {
if(shardedJedis!=null){
shardedJedis.close();
}
}
return false;
} /**
* 获取List
*
* @param key
* @return
*/
public List<String> lrange(String key) {
ShardedJedis shardedJedis = null;
try {
shardedJedis = shardedJedisPool.getResource();
return shardedJedis.lrange(key, 0, -1);
} catch (Exception ex) {
LOG.error("lrange error.", ex); } finally {
if(shardedJedis!=null){
shardedJedis.close();
}
}
return null;
}
/**
* 获取List
*
* @param key
* @return
*/
public List<Object> lrangeObject(String key) {
List<Object> objList=new ArrayList<Object>();
List<byte[]> list=lrangeByte( key) ;
if(list !=null &&list.size()>0){
for (int i=0;i<list.size();i++){
objList.add(SerializeUtil.deserialize(list.get(i)));
}
}
return objList;
}
/**
* 获取List
*
* @param key
* @return
*/
public List<byte[]> lrangeByte(String key) {
ShardedJedis shardedJedis = null;
try {
shardedJedis = shardedJedisPool.getResource(); return shardedJedis.lrange(key.getBytes(charset), 0, -1); } catch (Exception ex) {
LOG.error("lrange error.", ex); } finally {
if(shardedJedis!=null){
shardedJedis.close();
}
}
return null;
} public Object getValue(String key) {
Object ret = null;
ShardedJedis jedis = shardedJedisPool.getResource();
try { // 去redis中取回序列化后的对象
byte[] obj = jedis.get(serialize(key)); // 取回的对象反序列化
if (obj != null) {
ret = SerializeUtil.deserialize(obj);
}
} catch (Exception e) {
LOG.error("get error.", e);
} finally {
if(jedis!=null){
jedis.close();
}
}
return ret;
}
}

shardedJedisPool工具类的更多相关文章

  1. redis 工具类 单个redis、JedisPool 及多个redis、shardedJedisPool与spring的集成配置

    http://www.cnblogs.com/edisonfeng/p/3571870.html http://javacrazyer.iteye.com/blog/1840161 http://ww ...

  2. redis分布式工具类 ----RedisShardedPoolUtil

    这个是redis分布式的工具类,看非分布式的看  这里 说一下redis的分布式,分布式,无疑,肯定不是一台redis服务器.假如说,我们有两台redis服务器,一个6379端口,一个6380端口.那 ...

  3. Java操作Redis工具类

    依赖 jar 包 <dependency> <groupId>redis.clients</groupId> <artifactId>jedis< ...

  4. java中的redis工具类

    1.redis基础类 package com.qlchat.component.redis.template; import javax.annotation.PostConstruct; impor ...

  5. Java基础Map接口+Collections工具类

    1.Map中我们主要讲两个接口 HashMap  与   LinkedHashMap (1)其中LinkedHashMap是有序的  怎么存怎么取出来 我们讲一下Map的增删改查功能: /* * Ma ...

  6. Android—关于自定义对话框的工具类

    开发中有很多地方会用到自定义对话框,为了避免不必要的城府代码,在此总结出一个工具类. 弹出对话框的地方很多,但是都大同小异,不同无非就是提示内容或者图片不同,下面这个类是将提示内容和图片放到了自定义函 ...

  7. [转]Java常用工具类集合

    转自:http://blog.csdn.net/justdb/article/details/8653166 数据库连接工具类——仅仅获得连接对象 ConnDB.java package com.ut ...

  8. js常用工具类.

    一些js的工具类 复制代码 /** * Created by sevennight on 15-1-31. * js常用工具类 */ /** * 方法作用:[格式化时间] * 使用方法 * 示例: * ...

  9. Guava库介绍之实用工具类

    作者:Jack47 转载请保留作者和原文出处 欢迎关注我的微信公众账号程序员杰克,两边的文章会同步,也可以添加我的RSS订阅源. 本文是我写的Google开源的Java编程库Guava系列之一,主要介 ...

随机推荐

  1. python 中函数

    函数   def 函数名(形参):形参不用在前面定义,局部变量   参数      必须参数            必须以正确的顺序传参      关键字参数        加入关键字后可以不需要正确 ...

  2. 避免Autoclose和Autoshrink选项

    避免Autoclose和Autoshrink选项发布日期:2001年12月18日 问题:我在Microsoft SQL Server 2000资源工具包中读到了一个用于就应当避免使用的选项对所有数据库 ...

  3. solidity语言1

    合约(contract)由变量(variable).函数(functions).函数修饰符(function modifiers).事件(events).结构体类型(struct type).枚举类型 ...

  4. 【java开发系列】—— java输入输出流

    前言 任何语言输入输出流都是很重要的部分,比如从一个文件读入内容,进行分析,或者输出到另一个文件等等,都需要文件流的操作.这里简单介绍下reader,wirter,inputstream,output ...

  5. May 17th 2017 Week 20th Wednesday

    Men are nearly always willing to believe what they wish. 人总爱想入非非,把愿望变成现实. It is just the humancondit ...

  6. May 14th 2017 Week 20th Sunday

    A smooth sea never made a skillful mariner. 平静的海洋练不出熟练的水手. A smooth sea never made a skillful marine ...

  7. vue+node+mongoose踩过的坑

    1.当你在cmd中输入npm run dev的时候,出现这种错误 很有可能是目前的端口被占用了,可以把所有可能用到这个端口号的应用关闭或者你直接改一个新的端口号 修改端口的方法:新打开一个cmd,然后 ...

  8. 如何从ERP下载Sales BOM到CRM

    在ERP使用事务码CS01创建一个BOM,类型选择5 - Sales BOM: BOM的抬头维护material 1419,在BOM的component部分维护另外两个material 1421和14 ...

  9. Vim中 ctags 跳转直接跳到第一个匹配行的问题

    意图 用ctags搜索代码时, 用 ctrl + ] 后,只有一个匹配项直接跳转,有多个则列出所有匹配项选择跳转 问题 在 vim 中使用 ctags 是一个很令人舒服的事情,但有时一些默认的配置和不 ...

  10. 【[SCOI2009]粉刷匠】

    这好像是个暴力? 但是跑的挺快的 我们设\(dp[i][j][k]\)表示在第\(i\)行我们最远染到的位置是\(j\),这一行上一共染了\(k\)次最多能染对多少个格子 理性分析一下啊,每一行最多也 ...