一、基于RedisTemplate
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
/*
* Redis工具类
*/
@Component
public final class RedisUtil {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
// =============================common============================
/**
* 指定缓存失效时间
* @param key 键
* @param time 时间(秒)
* @return
*/
public boolean expire(String key, long time) {
try {
if (time > 0) {
redisTemplate.expire(key, time, TimeUnit.SECONDS);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 根据key 获取过期时间
* @param key 键 不能为null
* @return 时间(秒) 返回0代表为永久有效
*/
public long getExpire(String key) {
return redisTemplate.getExpire(key, TimeUnit.SECONDS);
}
/**
* 判断key是否存在
* @param key 键
* @return true 存在 false不存在
*/
public boolean hasKey(String key) {
try {
return redisTemplate.hasKey(key);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 删除缓存
* @param key 可以传一个值 或多个
*/
@SuppressWarnings("unchecked")
public void del(String... key) {
if (key != null && key.length > 0) {
if (key.length == 1) {
redisTemplate.delete(key[0]);
} else {
redisTemplate.delete(CollectionUtils.arrayToList(key));
}
}
}
// ============================String=============================
/**
* 普通缓存获取
* @param key 键
* @return 值
*/
public Object get(String key) {
return key == null ? null : redisTemplate.opsForValue().get(key);
}
/**
* 普通缓存放入
* @param key 键
* @param value 值
* @return true成功 false失败
*/
public boolean set(String key, Object value) {
try {
redisTemplate.opsForValue().set(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 普通缓存放入并设置时间
* @param key 键
* @param value 值
* @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
* @return true成功 false 失败
*/
public boolean set(String key, Object value, long time) {
try {
if (time > 0) {
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
} else {
set(key, value);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 递增
* @param key 键
* @param delta 要增加几(大于0)
* @return
*/
public long incr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException("递增因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, delta);
}
/**
* 递减
* @param key 键
* @param delta 要减少几(小于0)
* @return
*/
public long decr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException("递减因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, -delta);
}
// ================================Map=================================
/**
* HashGet
* @param key 键 不能为null
* @param item 项 不能为null
* @return 值
*/
public Object hget(String key, String item) {
return redisTemplate.opsForHash().get(key, item);
}
/**
* 获取hashKey对应的所有键值
* @param key 键
* @return 对应的多个键值
*/
public Map<Object, Object> hmget(String key) {
return redisTemplate.opsForHash().entries(key);
}
/**
* HashSet
* @param key 键
* @param map 对应多个键值
* @return true 成功 false 失败
*/
public boolean hmset(String key, Map<String, Object> map) {
try {
redisTemplate.opsForHash().putAll(key, map);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* HashSet 并设置时间
* @param key 键
* @param map 对应多个键值
* @param time 时间(秒)
* @return true成功 false失败
*/
public boolean hmset(String key, Map<String, Object> map, long time) {
try {
redisTemplate.opsForHash().putAll(key, map);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 向一张hash表中放入数据,如果不存在将创建
* @param key 键
* @param item 项
* @param value 值
* @return true 成功 false失败
*/
public boolean hset(String key, String item, Object value) {
try {
redisTemplate.opsForHash().put(key, item, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 向一张hash表中放入数据,如果不存在将创建
* @param key 键
* @param item 项
* @param value 值
* @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
* @return true 成功 false失败
*/
public boolean hset(String key, String item, Object value, long time) {
try {
redisTemplate.opsForHash().put(key, item, value);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 删除hash表中的值
* @param key 键 不能为null
* @param item 项 可以使多个 不能为null
*/
public void hdel(String key, Object... item) {
redisTemplate.opsForHash().delete(key, item);
}
/**
* 判断hash表中是否有该项的值
* @param key 键 不能为null
* @param item 项 不能为null
* @return true 存在 false不存在
*/
public boolean hHasKey(String key, String item) {
return redisTemplate.opsForHash().hasKey(key, item);
}
/**
* hash递增 如果不存在,就会创建一个 并把新增后的值返回
* @param key 键
* @param item 项
* @param by 要增加几(大于0)
* @return
*/
public double hincr(String key, String item, double by) {
return redisTemplate.opsForHash().increment(key, item, by);
}
/**
* hash递减
* @param key 键
* @param item 项
* @param by 要减少记(小于0)
* @return
*/
public double hdecr(String key, String item, double by) {
return redisTemplate.opsForHash().increment(key, item, -by);
}
// ============================set=============================
/**
* 根据key获取Set中的所有值
* @param key 键
* @return
*/
public Set<Object> sGet(String key) {
try {
return redisTemplate.opsForSet().members(key);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 根据value从一个set中查询,是否存在
* @param key 键
* @param value 值
* @return true 存在 false不存在
*/
public boolean sHasKey(String key, Object value) {
try {
return redisTemplate.opsForSet().isMember(key, value);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将数据放入set缓存
* @param key 键
* @param values 值 可以是多个
* @return 成功个数
*/
public long sSet(String key, Object... values) {
try {
return redisTemplate.opsForSet().add(key, values);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 将set数据放入缓存
* @param key 键
* @param time 时间(秒)
* @param values 值 可以是多个
* @return 成功个数
*/
public long sSetAndTime(String key, long time, Object... values) {
try {
Long count = redisTemplate.opsForSet().add(key, values);
if (time > 0)
expire(key, time);
return count;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 获取set缓存的长度
* @param key 键
* @return
*/
public long sGetSetSize(String key) {
try {
return redisTemplate.opsForSet().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 移除值为value的
* @param key 键
* @param values 值 可以是多个
* @return 移除的个数
*/
public long setRemove(String key, Object... values) {
try {
Long count = redisTemplate.opsForSet().remove(key, values);
return count;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
// ===============================list=================================
/**
* 获取list缓存的内容
* @param key 键
* @param start 开始
* @param end 结束 0 到 -1代表所有值
* @return
*/
public List<Object> lGet(String key, long start, long end) {
try {
return redisTemplate.opsForList().range(key, start, end);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 获取list缓存的长度
* @param key 键
* @return
*/
public long lGetListSize(String key) {
try {
return redisTemplate.opsForList().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 通过索引 获取list中的值
* @param key 键
* @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
* @return
*/
public Object lGetIndex(String key, long index) {
try {
return redisTemplate.opsForList().index(key, index);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 将list放入缓存
* @param key 键
* @param value 值
* @param time 时间(秒)
* @return
*/
public boolean lSet(String key, Object value) {
try {
redisTemplate.opsForList().rightPush(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将list放入缓存
* @param key 键
* @param value 值
* @param time 时间(秒)
* @return
*/
public boolean lSet(String key, Object value, long time) {
try {
redisTemplate.opsForList().rightPush(key, value);
if (time > 0)
expire(key, time);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将list放入缓存
* @param key 键
* @param value 值
* @param time 时间(秒)
* @return
*/
public boolean lSet(String key, List<Object> value) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将list放入缓存
*
* @param key 键
* @param value 值
* @param time 时间(秒)
* @return
*/
public boolean lSet(String key, List<Object> value, long time) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
if (time > 0)
expire(key, time);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 根据索引修改list中的某条数据
* @param key 键
* @param index 索引
* @param value 值
* @return
*/
public boolean lUpdateIndex(String key, long index, Object value) {
try {
redisTemplate.opsForList().set(key, index, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 移除N个值为value
* @param key 键
* @param count 移除多少个
* @param value 值
* @return 移除的个数
*/
public long lRemove(String key, long count, Object value) {
try {
Long remove = redisTemplate.opsForList().remove(key, count, value);
return remove;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
}
二、基于StringRedisTemplate
import org.springframework.data.redis.connection.DataType;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations.TypedTuple;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* Redis工具类
* */
public class RedisUtil {
private StringRedisTemplate redisTemplate;
public void setRedisTemplate(StringRedisTemplate redisTemplate) {
this.redisTemplate = redisTemplate;
}
public StringRedisTemplate getRedisTemplate() {
return this.redisTemplate;
}
/** -------------------key相关操作--------------------- */
/**
* 删除key
*
* @param key
*/
public void delete(String key) {
redisTemplate.delete(key);
}
/**
* 批量删除key
*
* @param keys
*/
public void delete(Collection<String> keys) {
redisTemplate.delete(keys);
}
/**
* 序列化key
*
* @param key
* @return
*/
public byte[] dump(String key) {
return redisTemplate.dump(key);
}
/**
* 是否存在key
*
* @param key
* @return
*/
public Boolean hasKey(String key) {
return redisTemplate.hasKey(key);
}
/**
* 设置过期时间
*
* @param key
* @param timeout
* @param unit
* @return
*/
public Boolean expire(String key, long timeout, TimeUnit unit) {
return redisTemplate.expire(key, timeout, unit);
}
/**
* 设置过期时间
*
* @param key
* @param date
* @return
*/
public Boolean expireAt(String key, Date date) {
return redisTemplate.expireAt(key, date);
}
/**
* 查找匹配的key
*
* @param pattern
* @return
*/
public Set<String> keys(String pattern) {
return redisTemplate.keys(pattern);
}
/**
* 将当前数据库的 key 移动到给定的数据库 db 当中
*
* @param key
* @param dbIndex
* @return
*/
public Boolean move(String key, int dbIndex) {
return redisTemplate.move(key, dbIndex);
}
/**
* 移除 key 的过期时间,key 将持久保持
*
* @param key
* @return
*/
public Boolean persist(String key) {
return redisTemplate.persist(key);
}
/**
* 返回 key 的剩余的过期时间
*
* @param key
* @param unit
* @return
*/
public Long getExpire(String key, TimeUnit unit) {
return redisTemplate.getExpire(key, unit);
}
/**
* 返回 key 的剩余的过期时间
*
* @param key
* @return
*/
public Long getExpire(String key) {
return redisTemplate.getExpire(key);
}
/**
* 从当前数据库中随机返回一个 key
*
* @return
*/
public String randomKey() {
return redisTemplate.randomKey();
}
/**
* 修改 key 的名称
*
* @param oldKey
* @param newKey
*/
public void rename(String oldKey, String newKey) {
redisTemplate.rename(oldKey, newKey);
}
/**
* 仅当 newkey 不存在时,将 oldKey 改名为 newkey
*
* @param oldKey
* @param newKey
* @return
*/
public Boolean renameIfAbsent(String oldKey, String newKey) {
return redisTemplate.renameIfAbsent(oldKey, newKey);
}
/**
* 返回 key 所储存的值的类型
*
* @param key
* @return
*/
public DataType type(String key) {
return redisTemplate.type(key);
}
/** -------------------string相关操作--------------------- */
/**
* 设置指定 key 的值
* @param key
* @param value
*/
public void set(String key, String value) {
redisTemplate.opsForValue().set(key, value);
}
/**
* 获取指定 key 的值
* @param key
* @return
*/
public String get(String key) {
return redisTemplate.opsForValue().get(key);
}
/**
* 返回 key 中字符串值的子字符
* @param key
* @param start
* @param end
* @return
*/
public String getRange(String key, long start, long end) {
return redisTemplate.opsForValue().get(key, start, end);
}
/**
* 将给定 key 的值设为 value ,并返回 key 的旧值(old value)
*
* @param key
* @param value
* @return
*/
public String getAndSet(String key, String value) {
return redisTemplate.opsForValue().getAndSet(key, value);
}
/**
* 对 key 所储存的字符串值,获取指定偏移量上的位(bit)
*
* @param key
* @param offset
* @return
*/
public Boolean getBit(String key, long offset) {
return redisTemplate.opsForValue().getBit(key, offset);
}
/**
* 批量获取
*
* @param keys
* @return
*/
public List<String> multiGet(Collection<String> keys) {
return redisTemplate.opsForValue().multiGet(keys);
}
/**
* 设置ASCII码, 字符串'a'的ASCII码是97, 转为二进制是'01100001', 此方法是将二进制第offset位值变为value
*
* @param key 位置
* @param value
* 值,true为1, false为0
* @return
*/
public boolean setBit(String key, long offset, boolean value) {
return redisTemplate.opsForValue().setBit(key, offset, value);
}
/**
* 将值 value 关联到 key ,并将 key 的过期时间设为 timeout
*
* @param key
* @param value
* @param timeout
* 过期时间
* @param unit
* 时间单位, 天:TimeUnit.DAYS 小时:TimeUnit.HOURS 分钟:TimeUnit.MINUTES
* 秒:TimeUnit.SECONDS 毫秒:TimeUnit.MILLISECONDS
*/
public void setEx(String key, String value, long timeout, TimeUnit unit) {
redisTemplate.opsForValue().set(key, value, timeout, unit);
}
/**
* 只有在 key 不存在时设置 key 的值
*
* @param key
* @param value
* @return 之前已经存在返回false,不存在返回true
*/
public boolean setIfAbsent(String key, String value) {
return redisTemplate.opsForValue().setIfAbsent(key, value);
}
/**
* 用 value 参数覆写给定 key 所储存的字符串值,从偏移量 offset 开始
*
* @param key
* @param value
* @param offset
* 从指定位置开始覆写
*/
public void setRange(String key, String value, long offset) {
redisTemplate.opsForValue().set(key, value, offset);
}
/**
* 获取字符串的长度
*
* @param key
* @return
*/
public Long size(String key) {
return redisTemplate.opsForValue().size(key);
}
/**
* 批量添加
*
* @param maps
*/
public void multiSet(Map<String, String> maps) {
redisTemplate.opsForValue().multiSet(maps);
}
/**
* 同时设置一个或多个 key-value 对,当且仅当所有给定 key 都不存在
*
* @param maps
* @return 之前已经存在返回false,不存在返回true
*/
public boolean multiSetIfAbsent(Map<String, String> maps) {
return redisTemplate.opsForValue().multiSetIfAbsent(maps);
}
/**
* 增加(自增长), 负数则为自减
*
* @param key
* @return
*/
public Long incrBy(String key, long increment) {
return redisTemplate.opsForValue().increment(key, increment);
}
/**
*
* @param key
* @return
*/
public Double incrByFloat(String key, double increment) {
return redisTemplate.opsForValue().increment(key, increment);
}
/**
* 追加到末尾
*
* @param key
* @param value
* @return
*/
public Integer append(String key, String value) {
return redisTemplate.opsForValue().append(key, value);
}
/** -------------------hash相关操作------------------------- */
/**
* 获取存储在哈希表中指定字段的值
*
* @param key
* @param field
* @return
*/
public Object hGet(String key, String field) {
return redisTemplate.opsForHash().get(key, field);
}
/**
* 获取所有给定字段的值
*
* @param key
* @return
*/
public Map<Object, Object> hGetAll(String key) {
return redisTemplate.opsForHash().entries(key);
}
/**
* 获取所有给定字段的值
*
* @param key
* @param fields
* @return
*/
public List<Object> hMultiGet(String key, Collection<Object> fields) {
return redisTemplate.opsForHash().multiGet(key, fields);
}
public void hPut(String key, String hashKey, String value) {
redisTemplate.opsForHash().put(key, hashKey, value);
}
public void hPutAll(String key, Map<String, String> maps) {
redisTemplate.opsForHash().putAll(key, maps);
}
/**
* 仅当hashKey不存在时才设置
*
* @param key
* @param hashKey
* @param value
* @return
*/
public Boolean hPutIfAbsent(String key, String hashKey, String value) {
return redisTemplate.opsForHash().putIfAbsent(key, hashKey, value);
}
/**
* 删除一个或多个哈希表字段
*
* @param key
* @param fields
* @return
*/
public Long hDelete(String key, Object... fields) {
return redisTemplate.opsForHash().delete(key, fields);
}
/**
* 查看哈希表 key 中,指定的字段是否存在
*
* @param key
* @param field
* @return
*/
public boolean hExists(String key, String field) {
return redisTemplate.opsForHash().hasKey(key, field);
}
/**
* 为哈希表 key 中的指定字段的整数值加上增量 increment
*
* @param key
* @param field
* @param increment
* @return
*/
public Long hIncrBy(String key, Object field, long increment) {
return redisTemplate.opsForHash().increment(key, field, increment);
}
/**
* 为哈希表 key 中的指定字段的整数值加上增量 increment
*
* @param key
* @param field
* @param delta
* @return
*/
public Double hIncrByFloat(String key, Object field, double delta) {
return redisTemplate.opsForHash().increment(key, field, delta);
}
/**
* 获取所有哈希表中的字段
*
* @param key
* @return
*/
public Set<Object> hKeys(String key) {
return redisTemplate.opsForHash().keys(key);
}
/**
* 获取哈希表中字段的数量
*
* @param key
* @return
*/
public Long hSize(String key) {
return redisTemplate.opsForHash().size(key);
}
/**
* 获取哈希表中所有值
*
* @param key
* @return
*/
public List<Object> hValues(String key) {
return redisTemplate.opsForHash().values(key);
}
/**
* 迭代哈希表中的键值对
*
* @param key
* @param options
* @return
*/
public Cursor<Entry<Object, Object>> hScan(String key, ScanOptions options) {
return redisTemplate.opsForHash().scan(key, options);
}
/** ------------------------list相关操作---------------------------- */
/**
* 通过索引获取列表中的元素
*
* @param key
* @param index
* @return
*/
public String lIndex(String key, long index) {
return redisTemplate.opsForList().index(key, index);
}
/**
* 获取列表指定范围内的元素
*
* @param key
* @param start
* 开始位置, 0是开始位置
* @param end
* 结束位置, -1返回所有
* @return
*/
public List<String> lRange(String key, long start, long end) {
return redisTemplate.opsForList().range(key, start, end);
}
/**
* 存储在list头部
*
* @param key
* @param value
* @return
*/
public Long lLeftPush(String key, String value) {
return redisTemplate.opsForList().leftPush(key, value);
}
/**
*
* @param key
* @param value
* @return
*/
public Long lLeftPushAll(String key, String... value) {
return redisTemplate.opsForList().leftPushAll(key, value);
}
/**
*
* @param key
* @param value
* @return
*/
public Long lLeftPushAll(String key, Collection<String> value) {
return redisTemplate.opsForList().leftPushAll(key, value);
}
/**
* 当list存在的时候才加入
*
* @param key
* @param value
* @return
*/
public Long lLeftPushIfPresent(String key, String value) {
return redisTemplate.opsForList().leftPushIfPresent(key, value);
}
/**
* 如果pivot存在,再pivot前面添加
*
* @param key
* @param pivot
* @param value
* @return
*/
public Long lLeftPush(String key, String pivot, String value) {
return redisTemplate.opsForList().leftPush(key, pivot, value);
}
/**
*
* @param key
* @param value
* @return
*/
public Long lRightPush(String key, String value) {
return redisTemplate.opsForList().rightPush(key, value);
}
/**
*
* @param key
* @param value
* @return
*/
public Long lRightPushAll(String key, String... value) {
return redisTemplate.opsForList().rightPushAll(key, value);
}
/**
*
* @param key
* @param value
* @return
*/
public Long lRightPushAll(String key, Collection<String> value) {
return redisTemplate.opsForList().rightPushAll(key, value);
}
/**
* 为已存在的列表添加值
*
* @param key
* @param value
* @return
*/
public Long lRightPushIfPresent(String key, String value) {
return redisTemplate.opsForList().rightPushIfPresent(key, value);
}
/**
* 在pivot元素的右边添加值
*
* @param key
* @param pivot
* @param value
* @return
*/
public Long lRightPush(String key, String pivot, String value) {
return redisTemplate.opsForList().rightPush(key, pivot, value);
}
/**
* 通过索引设置列表元素的值
*
* @param key
* @param index
* 位置
* @param value
*/
public void lSet(String key, long index, String value) {
redisTemplate.opsForList().set(key, index, value);
}
/**
* 移出并获取列表的第一个元素
*
* @param key
* @return 删除的元素
*/
public String lLeftPop(String key) {
return redisTemplate.opsForList().leftPop(key);
}
/**
* 移出并获取列表的第一个元素, 如果列表没有元素会阻塞列表直到等待超时或发现可弹出元素为止
*
* @param key
* @param timeout
* 等待时间
* @param unit
* 时间单位
* @return
*/
public String lBLeftPop(String key, long timeout, TimeUnit unit) {
return redisTemplate.opsForList().leftPop(key, timeout, unit);
}
/**
* 移除并获取列表最后一个元素
*
* @param key
* @return 删除的元素
*/
public String lRightPop(String key) {
return redisTemplate.opsForList().rightPop(key);
}
/**
* 移出并获取列表的最后一个元素, 如果列表没有元素会阻塞列表直到等待超时或发现可弹出元素为止
*
* @param key
* @param timeout
* 等待时间
* @param unit
* 时间单位
* @return
*/
public String lBRightPop(String key, long timeout, TimeUnit unit) {
return redisTemplate.opsForList().rightPop(key, timeout, unit);
}
/**
* 移除列表的最后一个元素,并将该元素添加到另一个列表并返回
*
* @param sourceKey
* @param destinationKey
* @return
*/
public String lRightPopAndLeftPush(String sourceKey, String destinationKey) {
return redisTemplate.opsForList().rightPopAndLeftPush(sourceKey,
destinationKey);
}
/**
* 从列表中弹出一个值,将弹出的元素插入到另外一个列表中并返回它; 如果列表没有元素会阻塞列表直到等待超时或发现可弹出元素为止
*
* @param sourceKey
* @param destinationKey
* @param timeout
* @param unit
* @return
*/
public String lBRightPopAndLeftPush(String sourceKey, String destinationKey,
long timeout, TimeUnit unit) {
return redisTemplate.opsForList().rightPopAndLeftPush(sourceKey,
destinationKey, timeout, unit);
}
/**
* 删除集合中值等于value得元素
*
* @param key
* @param index
* index=0, 删除所有值等于value的元素; index>0, 从头部开始删除第一个值等于value的元素;
* index<0, 从尾部开始删除第一个值等于value的元素;
* @param value
* @return
*/
public Long lRemove(String key, long index, String value) {
return redisTemplate.opsForList().remove(key, index, value);
}
/**
* 裁剪list
*
* @param key
* @param start
* @param end
*/
public void lTrim(String key, long start, long end) {
redisTemplate.opsForList().trim(key, start, end);
}
/**
* 获取列表长度
*
* @param key
* @return
*/
public Long lLen(String key) {
return redisTemplate.opsForList().size(key);
}
/** --------------------set相关操作-------------------------- */
/**
* set添加元素
*
* @param key
* @param values
* @return
*/
public Long sAdd(String key, String... values) {
return redisTemplate.opsForSet().add(key, values);
}
/**
* set移除元素
*
* @param key
* @param values
* @return
*/
public Long sRemove(String key, Object... values) {
return redisTemplate.opsForSet().remove(key, values);
}
/**
* 移除并返回集合的一个随机元素
*
* @param key
* @return
*/
public String sPop(String key) {
return redisTemplate.opsForSet().pop(key);
}
/**
* 将元素value从一个集合移到另一个集合
*
* @param key
* @param value
* @param destKey
* @return
*/
public Boolean sMove(String key, String value, String destKey) {
return redisTemplate.opsForSet().move(key, value, destKey);
}
/**
* 获取集合的大小
*
* @param key
* @return
*/
public Long sSize(String key) {
return redisTemplate.opsForSet().size(key);
}
/**
* 判断集合是否包含value
*
* @param key
* @param value
* @return
*/
public Boolean sIsMember(String key, Object value) {
return redisTemplate.opsForSet().isMember(key, value);
}
/**
* 获取两个集合的交集
*
* @param key
* @param otherKey
* @return
*/
public Set<String> sIntersect(String key, String otherKey) {
return redisTemplate.opsForSet().intersect(key, otherKey);
}
/**
* 获取key集合与多个集合的交集
*
* @param key
* @param otherKeys
* @return
*/
public Set<String> sIntersect(String key, Collection<String> otherKeys) {
return redisTemplate.opsForSet().intersect(key, otherKeys);
}
/**
* key集合与otherKey集合的交集存储到destKey集合中
*
* @param key
* @param otherKey
* @param destKey
* @return
*/
public Long sIntersectAndStore(String key, String otherKey, String destKey) {
return redisTemplate.opsForSet().intersectAndStore(key, otherKey,
destKey);
}
/**
* key集合与多个集合的交集存储到destKey集合中
*
* @param key
* @param otherKeys
* @param destKey
* @return
*/
public Long sIntersectAndStore(String key, Collection<String> otherKeys,
String destKey) {
return redisTemplate.opsForSet().intersectAndStore(key, otherKeys,
destKey);
}
/**
* 获取两个集合的并集
*
* @param key
* @param otherKeys
* @return
*/
public Set<String> sUnion(String key, String otherKeys) {
return redisTemplate.opsForSet().union(key, otherKeys);
}
/**
* 获取key集合与多个集合的并集
*
* @param key
* @param otherKeys
* @return
*/
public Set<String> sUnion(String key, Collection<String> otherKeys) {
return redisTemplate.opsForSet().union(key, otherKeys);
}
/**
* key集合与otherKey集合的并集存储到destKey中
*
* @param key
* @param otherKey
* @param destKey
* @return
*/
public Long sUnionAndStore(String key, String otherKey, String destKey) {
return redisTemplate.opsForSet().unionAndStore(key, otherKey, destKey);
}
/**
* key集合与多个集合的并集存储到destKey中
*
* @param key
* @param otherKeys
* @param destKey
* @return
*/
public Long sUnionAndStore(String key, Collection<String> otherKeys,
String destKey) {
return redisTemplate.opsForSet().unionAndStore(key, otherKeys, destKey);
}
/**
* 获取两个集合的差集
*
* @param key
* @param otherKey
* @return
*/
public Set<String> sDifference(String key, String otherKey) {
return redisTemplate.opsForSet().difference(key, otherKey);
}
/**
* 获取key集合与多个集合的差集
*
* @param key
* @param otherKeys
* @return
*/
public Set<String> sDifference(String key, Collection<String> otherKeys) {
return redisTemplate.opsForSet().difference(key, otherKeys);
}
/**
* key集合与otherKey集合的差集存储到destKey中
*
* @param key
* @param otherKey
* @param destKey
* @return
*/
public Long sDifference(String key, String otherKey, String destKey) {
return redisTemplate.opsForSet().differenceAndStore(key, otherKey,
destKey);
}
/**
* key集合与多个集合的差集存储到destKey中
*
* @param key
* @param otherKeys
* @param destKey
* @return
*/
public Long sDifference(String key, Collection<String> otherKeys,
String destKey) {
return redisTemplate.opsForSet().differenceAndStore(key, otherKeys,
destKey);
}
/**
* 获取集合所有元素
*
* @param key
* @return
*/
public Set<String> setMembers(String key) {
return redisTemplate.opsForSet().members(key);
}
/**
* 随机获取集合中的一个元素
*
* @param key
* @return
*/
public String sRandomMember(String key) {
return redisTemplate.opsForSet().randomMember(key);
}
/**
* 随机获取集合中count个元素
*
* @param key
* @param count
* @return
*/
public List<String> sRandomMembers(String key, long count) {
return redisTemplate.opsForSet().randomMembers(key, count);
}
/**
* 随机获取集合中count个元素并且去除重复的
*
* @param key
* @param count
* @return
*/
public Set<String> sDistinctRandomMembers(String key, long count) {
return redisTemplate.opsForSet().distinctRandomMembers(key, count);
}
/**
*
* @param key
* @param options
* @return
*/
public Cursor<String> sScan(String key, ScanOptions options) {
return redisTemplate.opsForSet().scan(key, options);
}
/**------------------zSet相关操作--------------------------------*/
/**
* 添加元素,有序集合是按照元素的score值由小到大排列
*
* @param key
* @param value
* @param score
* @return
*/
public Boolean zAdd(String key, String value, double score) {
return redisTemplate.opsForZSet().add(key, value, score);
}
/**
*
* @param key
* @param values
* @return
*/
public Long zAdd(String key, Set<TypedTuple<String>> values) {
return redisTemplate.opsForZSet().add(key, values);
}
/**
*
* @param key
* @param values
* @return
*/
public Long zRemove(String key, Object... values) {
return redisTemplate.opsForZSet().remove(key, values);
}
/**
* 增加元素的score值,并返回增加后的值
*
* @param key
* @param value
* @param delta
* @return
*/
public Double zIncrementScore(String key, String value, double delta) {
return redisTemplate.opsForZSet().incrementScore(key, value, delta);
}
/**
* 返回元素在集合的排名,有序集合是按照元素的score值由小到大排列
*
* @param key
* @param value
* @return 0表示第一位
*/
public Long zRank(String key, Object value) {
return redisTemplate.opsForZSet().rank(key, value);
}
/**
* 返回元素在集合的排名,按元素的score值由大到小排列
*
* @param key
* @param value
* @return
*/
public Long zReverseRank(String key, Object value) {
return redisTemplate.opsForZSet().reverseRank(key, value);
}
/**
* 获取集合的元素, 从小到大排序
*
* @param key
* @param start
* 开始位置
* @param end
* 结束位置, -1查询所有
* @return
*/
public Set<String> zRange(String key, long start, long end) {
return redisTemplate.opsForZSet().range(key, start, end);
}
/**
* 获取集合元素, 并且把score值也获取
*
* @param key
* @param start
* @param end
* @return
*/
public Set<TypedTuple<String>> zRangeWithScores(String key, long start,
long end) {
return redisTemplate.opsForZSet().rangeWithScores(key, start, end);
}
/**
* 根据Score值查询集合元素
*
* @param key
* @param min
* 最小值
* @param max
* 最大值
* @return
*/
public Set<String> zRangeByScore(String key, double min, double max) {
return redisTemplate.opsForZSet().rangeByScore(key, min, max);
}
/**
* 根据Score值查询集合元素, 从小到大排序
*
* @param key
* @param min
* 最小值
* @param max
* 最大值
* @return
*/
public Set<TypedTuple<String>> zRangeByScoreWithScores(String key,
double min, double max) {
return redisTemplate.opsForZSet().rangeByScoreWithScores(key, min, max);
}
/**
*
* @param key
* @param min
* @param max
* @param start
* @param end
* @return
*/
public Set<TypedTuple<String>> zRangeByScoreWithScores(String key,
double min, double max, long start, long end) {
return redisTemplate.opsForZSet().rangeByScoreWithScores(key, min, max,
start, end);
}
/**
* 获取集合的元素, 从大到小排序
*
* @param key
* @param start
* @param end
* @return
*/
public Set<String> zReverseRange(String key, long start, long end) {
return redisTemplate.opsForZSet().reverseRange(key, start, end);
}
/**
* 获取集合的元素, 从大到小排序, 并返回score值
*
* @param key
* @param start
* @param end
* @return
*/
public Set<TypedTuple<String>> zReverseRangeWithScores(String key,
long start, long end) {
return redisTemplate.opsForZSet().reverseRangeWithScores(key, start,
end);
}
/**
* 根据Score值查询集合元素, 从大到小排序
*
* @param key
* @param min
* @param max
* @return
*/
public Set<String> zReverseRangeByScore(String key, double min,
double max) {
return redisTemplate.opsForZSet().reverseRangeByScore(key, min, max);
}
/**
* 根据Score值查询集合元素, 从大到小排序
*
* @param key
* @param min
* @param max
* @return
*/
public Set<TypedTuple<String>> zReverseRangeByScoreWithScores(
String key, double min, double max) {
return redisTemplate.opsForZSet().reverseRangeByScoreWithScores(key,
min, max);
}
/**
*
* @param key
* @param min
* @param max
* @param start
* @param end
* @return
*/
public Set<String> zReverseRangeByScore(String key, double min,
double max, long start, long end) {
return redisTemplate.opsForZSet().reverseRangeByScore(key, min, max,
start, end);
}
/**
* 根据score值获取集合元素数量
*
* @param key
* @param min
* @param max
* @return
*/
public Long zCount(String key, double min, double max) {
return redisTemplate.opsForZSet().count(key, min, max);
}
/**
* 获取集合大小
*
* @param key
* @return
*/
public Long zSize(String key) {
return redisTemplate.opsForZSet().size(key);
}
/**
* 获取集合大小
*
* @param key
* @return
*/
public Long zZCard(String key) {
return redisTemplate.opsForZSet().zCard(key);
}
/**
* 获取集合中value元素的score值
*
* @param key
* @param value
* @return
*/
public Double zScore(String key, Object value) {
return redisTemplate.opsForZSet().score(key, value);
}
/**
* 移除指定索引位置的成员
*
* @param key
* @param start
* @param end
* @return
*/
public Long zRemoveRange(String key, long start, long end) {
return redisTemplate.opsForZSet().removeRange(key, start, end);
}
/**
* 根据指定的score值的范围来移除成员
*
* @param key
* @param min
* @param max
* @return
*/
public Long zRemoveRangeByScore(String key, double min, double max) {
return redisTemplate.opsForZSet().removeRangeByScore(key, min, max);
}
/**
* 获取key和otherKey的并集并存储在destKey中
*
* @param key
* @param otherKey
* @param destKey
* @return
*/
public Long zUnionAndStore(String key, String otherKey, String destKey) {
return redisTemplate.opsForZSet().unionAndStore(key, otherKey, destKey);
}
/**
*
* @param key
* @param otherKeys
* @param destKey
* @return
*/
public Long zUnionAndStore(String key, Collection<String> otherKeys,
String destKey) {
return redisTemplate.opsForZSet()
.unionAndStore(key, otherKeys, destKey);
}
/**
* 交集
*
* @param key
* @param otherKey
* @param destKey
* @return
*/
public Long zIntersectAndStore(String key, String otherKey,
String destKey) {
return redisTemplate.opsForZSet().intersectAndStore(key, otherKey,
destKey);
}
/**
* 交集
*
* @param key
* @param otherKeys
* @param destKey
* @return
*/
public Long zIntersectAndStore(String key, Collection<String> otherKeys,
String destKey) {
return redisTemplate.opsForZSet().intersectAndStore(key, otherKeys,
destKey);
}
/**
*
* @param key
* @param options
* @return
*/
public Cursor<TypedTuple<String>> zScan(String key, ScanOptions options) {
return redisTemplate.opsForZSet().scan(key, options);
}
}
三、基于jedis
import com.jyf.redis.common.config.MyJedisPoolConfig;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.Pipeline;
import redis.clients.jedis.Tuple;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* 基于jedis的redis操作工具类
*/
public final class RedisUtils {
/*
除了该工具类提供的方法外,还可以在外面调用getJedis()方法,获取到jedis实例后,调用它原生的api来操作
*/
/**
* 获取jedis对象,并选择redis库。jedis默认是0号库,可传入1-16之间的数选择库存放数据
* 原则上使用一个redis库存放数据,通过特定的key的命令规则来区分不同的数据就行了。
*
* @param index redis库号。使用可变参数的目的就是该参数可传可不传。
* @return 返回jedis对象
*/
public static Jedis getJedis(int... index) {
Jedis jedis = MyJedisPoolConfig.getJedisPool().getResource();
if (index != null && index.length > 0) {
if (index[0] > 0 && index[0] <= 16){
jedis.select(index[0]);
}
}
return jedis;
}
/*######################## key的操作 ################################*/
/**
* 根据pattern返回当前库中的key
*
* @param pattern
* @return
*/
public static Set<String> keys(String pattern) {
Jedis jedis = null;
Set<String> keys = null;
try {
jedis = getJedis();
keys = jedis.keys(pattern);
}finally {
if (jedis != null){
jedis.close();
}
}
return keys;
}
/**
* 删除一个或多个key
*
* @param key 一个或多个key
*/
public static Long del(String... key) {
Jedis jedis = null;
Long delNum = 0L;
try {
jedis = getJedis();
delNum =jedis.del(key);
}finally {
if (jedis != null){
jedis.close();
}
}
return delNum;
}
/**
* 批量删除
* @param keyList 要删除的key的集合
*/
public static void mdel(List<String> keyList){
Jedis jedis = getJedis();
//获取pipeline
Pipeline pipeline = jedis.pipelined();
for (String key : keyList) {
pipeline.del(key);
}
//执行结果同步,这样才能保证结果的正确性。实际上不执行该方法也执行了上面的命令,但是结果确不一定完全正确。
//注意
pipeline.sync();
//关闭连接
jedis.close();
}
/**
* 判断某个key是否还存在
*
* @param key key
* @return
*/
public static Boolean exists(String key) {
Jedis jedis = null;
Boolean flag = false;
try {
jedis = getJedis();
flag = jedis.exists(key);
}finally {
if (jedis != null){
jedis.close();
}
}
return flag;
}
/**
* 设置某个key的过期时间,单位秒
*
* @param key key
* @param seconds 过期时间秒
*/
public static void expire(String key, int seconds) {
Jedis jedis = null;
try {
jedis = getJedis();
jedis.expire(key, seconds);
}finally {
if (jedis != null){
jedis.close();
}
}
}
/**
* 查看某个key还有几秒过期,-1表示永不过期 ,-2表示已过期
*
* @param key key
* @return
*/
public static Long timeToLive(String key) {
Jedis jedis = null;
Long ttl;
try {
jedis = getJedis();
ttl = jedis.ttl(key);
}finally {
if (jedis != null){
jedis.close();
}
}
return ttl;
}
/**
* 查看某个key对应的value的类型
*
* @param key
* @return
*/
public static String type(String key) {
Jedis jedis = null;
String type = null;
try {
jedis = getJedis();
type = jedis.type(key);
}finally {
if (jedis != null){
jedis.close();
}
}
return type;
}
/*######################## string(字符串)的操作 ####################*/
/**
* 获取某个key的value,类型要对,只能value是string的才能获取
*
* @param key
* @return
*/
public static String get(String key) {
Jedis jedis = null;
String value = null;
try {
jedis = getJedis();
value = jedis.get(key);
}finally {
if (jedis != null){
jedis.close();
}
}
return value;
}
/**
* 设置某个key的value
*
* @param key
* @param value
*/
public static void set(String key, String value) {
Jedis jedis = null;
try {
jedis = getJedis();
jedis.set(key, value);
}finally {
if (jedis != null){
jedis.close();
}
}
}
/**
* 字符串后追加内容
*
* @param key key
* @param appendContent 要追加的内容
*/
public static void append(String key, String appendContent) {
Jedis jedis = null;
try {
jedis = getJedis();
jedis.append(key, appendContent);
}finally {
if (jedis != null){
jedis.close();
}
}
}
/**
* 返回key的value的长度
*
* @param key
* @return
*/
public static Long strlen(String key) {
Jedis jedis = null;
Long strLen = 0L;
try {
jedis = getJedis();
strLen = jedis.strlen(key);
}finally {
if (jedis != null){
jedis.close();
}
}
return strLen;
}
/**
* value 加1 必
* 须是字符型数字
* @param key
* @return 增加后的值
*/
public static Long incr(String key) {
Jedis jedis = null;
Long incrResult = 0L;
try {
jedis = getJedis();
incrResult = jedis.incr(key);
}finally {
if (jedis != null){
jedis.close();
}
}
return incrResult;
}
/**
* value 减1 必须是字符型数字
*
* @param key
* @return
*/
public static Long decr(String key) {
Jedis jedis = null;
Long decrResult = 0L;
try {
jedis = getJedis();
decrResult = jedis.decr(key);
}finally {
if (jedis != null){
jedis.close();
}
}
return decrResult;
}
/**
* value 加increment
*
* @param key key
* @param increment 加几
* @return
*/
public static Long incrby(String key, int increment) {
Jedis jedis = null;
Long incrByResult = 0L;
try {
jedis = getJedis();
incrByResult = jedis.incrBy(key, increment);
}finally {
if (jedis != null){
jedis.close();
}
}
return incrByResult;
}
/**
* value 减increment
*
* @param key
* @param increment
* @return
*/
public static Long decrby(String key, int increment) {
Jedis jedis = null;
Long decrByResult = 0L;
try {
jedis = getJedis();
decrByResult = jedis.decrBy(key, increment);
}finally {
if (jedis != null){
jedis.close();
}
}
return decrByResult;
}
/**
* 给某个key设置过期时间和value,成功返回OK
*
* @param key key
* @param seconds 过期时间秒
* @param value 设置的值
* @return
*/
public static String setex(String key, int seconds, String value) {
Jedis jedis = null;
String result = null;
try {
jedis = getJedis();
result = jedis.setex(key, seconds, value);
}finally {
if (jedis != null){
jedis.close();
}
}
return result;
}
/*######################## list(列表)的操作 #######################*/
//lpush rpush lpop rpop lrange lindex llen lset
/**
* 从左边向列表中添加值
*
* @param key key
* @param str 要添加的值
*/
public static void lpush(String key, String str) {
Jedis jedis = null;
try {
jedis = getJedis();
jedis.lpush(key, str);
}finally {
if (jedis != null){
jedis.close();
}
}
}
/**
* 从右边向列表中添加值
*
* @param key key
* @param str 要添加的值
*/
public static void rpush(String key, String str) {
Jedis jedis = null;
try {
jedis = getJedis();
jedis.rpush(key, str);
}finally {
if (jedis != null){
jedis.close();
}
}
}
/**
* 从左边取出一个列表中的值
*
* @param key
* @return
*/
public static String lpop(String key) {
Jedis jedis = null;
String lpop = null;
try {
jedis = getJedis();
lpop = jedis.lpop(key);
}finally {
if (jedis != null){
jedis.close();
}
}
return lpop;
}
/**
* 从右边取出一个列表中的值
*
* @param key
* @return
*/
public static String rpop(String key) {
Jedis jedis = null;
String rpop = null;
try {
jedis = getJedis();
rpop = jedis.rpop(key);
}finally {
if (jedis != null){
jedis.close();
}
}
return rpop;
}
/**
* 取出列表中指定范围内的值,0 到 -1 表示全部
*
* @param key
* @param startIndex
* @param endIndex
* @return
*/
public static List<String> lrange(String key, int startIndex, int endIndex) {
Jedis jedis = null;
List<String> result = null;
try {
jedis = getJedis();
result = jedis.lrange(key, startIndex, endIndex);
}finally {
if (jedis != null){
jedis.close();
}
}
return result;
}
/**
* 返回某列表指定索引位置的值
*
* @param key 列表key
* @param index 索引位置
* @return
*/
public static String lindex(String key, int index) {
Jedis jedis = null;
String lindex = null;
try {
jedis = getJedis();
lindex = jedis.lindex(key, index);
}finally {
if (jedis != null){
jedis.close();
}
}
return lindex;
}
/**
* 返回某列表的长度
*
* @param key
* @return
*/
public static Long llen(String key) {
Jedis jedis = null;
Long llen = 0L;
try {
jedis = getJedis();
llen = jedis.llen(key);
}finally {
if (jedis != null){
jedis.close();
}
}
return llen;
}
/**
* 给某列表指定位置设置为指定的值
*
* @param key
* @param index
* @param str
*/
public static void lset(String key, Long index, String str) {
Jedis jedis = null;
try {
jedis = getJedis();
jedis.lset(key, index, str);
}finally {
if (jedis != null){
jedis.close();
}
}
}
/**
* 对列表进行剪裁,保留指定闭区间的元素(索引位置也会重排)
* @param key 列表key
* @param startIndex 开始索引位置
* @param endIndex 结束索引位置
*/
public static void ltrim(String key,Integer startIndex,Integer endIndex){
Jedis jedis = null;
try {
jedis = getJedis();
jedis.ltrim(key, startIndex, endIndex);
}finally {
if (jedis != null){
jedis.close();
}
}
}
/**
* 从列表的左边阻塞弹出一个元素
* @param key 列表的key
* @param timeout 阻塞超时时间,0表示若没有元素就永久阻塞
* @return
*/
public static List<String> blpop(String key,Integer timeout){
Jedis jedis = null;
List<String> valueList = null;
try {
jedis = getJedis();
valueList = jedis.blpop(timeout, key);
}finally {
if (jedis != null){
jedis.close();
}
}
return valueList;
}
/**
* 从列表的右边阻塞弹出一个元素
* @param key 列表的key
* @param timeout 阻塞超时时间,0表示若没有元素就永久阻塞
* @return
*/
public static List<String> brpop(String key,Integer timeout){
Jedis jedis = null;
List<String> valueList = null;
try {
jedis = getJedis();
valueList = jedis.brpop(timeout, key);
}finally {
if (jedis != null){
jedis.close();
}
}
return valueList;
}
/*######################## hash(哈希表)的操作 #######################*/
//hset hget hmset hmget hgetall hdel hkeys hvals hexists hincrby
/**
* 给某个hash表设置一个键值对
*
* @param key
* @param field
* @param value
*/
public static void hset(String key, String field, String value) {
Jedis jedis = null;
try {
jedis = getJedis();
jedis.hset(key, field, value);
}finally {
if (jedis != null){
jedis.close();
}
}
}
/**
* 取出某个hash表中某个field对应的value
*
* @param key key
* @param field field
* @return
*/
public static String hget(String key, String field) {
Jedis jedis = null;
String hget = null;
try {
jedis = getJedis();
hget = jedis.hget(key, field);
}finally {
if (jedis != null){
jedis.close();
}
}
return hget;
}
/**
* 某个hash表设置一个或多个键值对
*
* @param key
* @param kvMap
*/
public static void hmset(String key, Map<String, String> kvMap) {
Jedis jedis = null;
try {
jedis = getJedis();
jedis.hmset(key, kvMap);
}finally {
if (jedis != null){
jedis.close();
}
}
}
/**
* 取出某个hash表中任意多个key对应的value的集合
*
* @param key
* @param fields
* @return
*/
public static List<String> hmget(String key, String... fields) {
Jedis jedis = null;
List<String> hmget = null;
try {
jedis = getJedis();
hmget = jedis.hmget(key, fields);
}finally {
if (jedis != null){
jedis.close();
}
}
return hmget;
}
/**
* 取出某个hash表中所有的键值对
*
* @param key
* @return
*/
public static Map<String, String> hgetall(String key) {
Jedis jedis = null;
Map<String, String> kvMap = null;
try {
jedis = getJedis();
kvMap = jedis.hgetAll(key);
}finally {
if (jedis != null){
jedis.close();
}
}
return kvMap;
}
/**
* 判断某个hash表中的某个key是否存在
*
* @param key
* @param field
* @return
*/
public static Boolean hexists(String key, String field) {
Jedis jedis = null;
Boolean exists = null;
try {
jedis = getJedis();
exists = jedis.hexists(key, field);
}finally {
if (jedis != null){
jedis.close();
}
}
return exists;
}
/**
* 返回某个hash表中所有的key
*
* @param key
* @return
*/
public static Set<String> hkeys(String key) {
Jedis jedis = null;
Set<String> keys = null;
try {
jedis = getJedis();
keys = jedis.hkeys(key);
}finally {
if (jedis != null){
jedis.close();
}
}
return keys;
}
/**
* 返回某个hash表中所有的value
*
* @param key
* @return
*/
public static List<String> hvals(String key) {
Jedis jedis = null;
List<String> hvals = null;
try {
jedis = getJedis();
hvals = jedis.hvals(key);
}finally {
if (jedis != null){
jedis.close();
}
}
return hvals;
}
/**
* 删除某个hash表中的一个或多个键值对
*
* @param key
* @param fields
*/
public static void hdel(String key, String... fields) {
Jedis jedis = null;
try {
jedis = getJedis();
jedis.hdel(key, fields);
}finally {
if (jedis != null){
jedis.close();
}
}
}
/**
* 给某个hash表中的某个field的value增加多少
*
* @param key hash表的key
* @param field 表中的某个field
* @param increment 增加多少
* @return
*/
public static Long hincrby(String key, String field, Long increment) {
Jedis jedis = null;
Long result = null;
try {
jedis = getJedis();
result = jedis.hincrBy(key, field, increment);
}finally {
if (jedis != null){
jedis.close();
}
}
return result;
}
/*######################## set(集合)的操作 ###########################*/
/**
* 往set集合中添加一个或多个元素
* @param key key
* @param members 要添加的元素
* @return 添加成功的元素个数
*/
public static Long sadd(String key,String... members){
Jedis jedis = null;
Long num = 0L;
try {
jedis = getJedis();
num = jedis.sadd(key, members);
}finally {
if (jedis != null){
jedis.close();
}
}
return num;
}
/**
* 返回set集合中的所有元素,顺序与加入时的顺序一致
* @param key key
* @return
*/
public static Set<String> smembers(String key){
Jedis jedis = null;
Set<String> members = null;
try {
jedis = getJedis();
members = jedis.smembers(key);
}finally {
if (jedis != null){
jedis.close();
}
}
return members;
}
/**
* 判断集合中是否存在某个元素
* @param key key
* @param member 某个元素
* @return true存在,false不存在
*/
public static Boolean sismember(String key,String member){
Jedis jedis = null;
Boolean isMember = false;
try {
jedis = getJedis();
isMember = jedis.sismember(key, member);
}finally {
if (jedis != null){
jedis.close();
}
}
return isMember;
}
/**
* 返回set集合的长度
* @param key key
* @return
*/
public static Long scard(String key){
Jedis jedis = null;
Long len = 0L;
try {
jedis = getJedis();
len = jedis.scard(key);
}finally {
if (jedis != null){
jedis.close();
}
}
return len;
}
/**
* 删除set集合中指定的一个或多个元素
* @param key
* @param members 要删除的元素
* @return 删除成功的元素个数
*/
public static Long srem(String key,String... members){
Jedis jedis = null;
Long num = 0L;
try {
jedis = getJedis();
num = jedis.srem(key,members);
}finally {
if (jedis != null){
jedis.close();
}
}
return num;
}
/**
* 将key1中的元素key1Member移动到key2中
* @param key1 来源集合key
* @param key2 目的地集合key
* @param key1Member key1中的元素
* @return 1成功,0失败
*/
public static Long smove(String key1,String key2,String key1Member){
Jedis jedis = null;
Long num = 0L;
try {
jedis = getJedis();
num = jedis.smove(key1,key2,key1Member);
}finally {
if (jedis != null){
jedis.close();
}
}
return num;
}
/**
* 随机查询返回集合中的指定个数的元素(若count为负数,返回的元素可能会重复)
* @param key key
* @param count 要查询返回的元素个数
* @return 元素list集合
*/
public static List<String> srandmember(String key,int count){
Jedis jedis = null;
List<String> members = null;
try {
jedis = getJedis();
members = jedis.srandmember(key,count);
}finally {
if (jedis != null){
jedis.close();
}
}
return members;
}
/**
* 从set集合中随机弹出指定个数个元素
* @param key key
* @param count 要弹出的个数
* @return 随机弹出的元素
*/
public static Set<String> spop(String key,int count){
Jedis jedis = null;
Set<String> members = null;
try {
jedis = getJedis();
members = jedis.spop(key,count);
}finally {
if (jedis != null){
jedis.close();
}
}
return members;
}
/**
* 求交集,返回多个set集合相交的部分
* @param setKeys 多个set集合的key
* @return 相交的元素集合
*/
public static Set<String> sinter(String... setKeys){
Jedis jedis = null;
Set<String> members = null;
try {
jedis = getJedis();
members = jedis.sinter(setKeys);
}finally {
if (jedis != null){
jedis.close();
}
}
return members;
}
/**
* 求并集,求几个set集合的并集(因为set中不会有重复的元素,合并后的集合也不会有重复的元素)
* @param setKeys 多个set的key
* @return 合并后的集合
*/
public static Set<String> sunion(String... setKeys){
Jedis jedis = null;
Set<String> members = null;
try {
jedis = getJedis();
members = jedis.sunion(setKeys);
}finally {
if (jedis != null){
jedis.close();
}
}
return members;
}
/**
* 求差集,求几个集合之间的差集
* @param setKeys 多个set的key
* @return 差集
*/
public static Set<String> sdiff(String... setKeys){
Jedis jedis = null;
Set<String> members = null;
try {
jedis = getJedis();
members = jedis.sdiff(setKeys);
}finally {
if (jedis != null){
jedis.close();
}
}
return members;
}
/*######################## zset(有序集合)的操作 #######################*/
/**
* 添加一个元素到zset
* @param key key
* @param score 元素的分数
* @param member 元素
* @return 成功添加的元素个数
*/
public static Long zadd(String key,double score, String member){
Jedis jedis = null;
Long num = null;
try {
jedis = getJedis();
num = jedis.zadd(key,score,member);
}finally {
if (jedis != null){
jedis.close();
}
}
return num;
}
/**
* 添加一个或多个元素到zset
* @param key key
* @param memberScores 元素和分数的map集合,map的k是元素,v是分数
* @return 成功添加的元素个数
*/
public static Long zadd(String key,Map<String,Double> memberScores){
Jedis jedis = null;
Long num = null;
try {
jedis = getJedis();
num = jedis.zadd(key,memberScores);
}finally {
if (jedis != null){
jedis.close();
}
}
return num;
}
/**
* 查询指定闭区间的元素(根据分数升序)
* (0,-1表示全部)
* @param key zset的key
* @param start 开始区间
* @param end 结束区间
* @return 元素集合
*/
public static Set<String> zrange(String key, long start, long end){
Jedis jedis = null;
Set<String> ascResult = null;
try {
jedis = getJedis();
ascResult = jedis.zrange(key,start,end);
}finally {
if (jedis != null){
jedis.close();
}
}
return ascResult;
}
/**
* 查询指定闭区间的元素,带着分数
* (0,-1表示全部)
* @param key zset的key
* @param start 开始区间
* @param end 结束区间
* @return 元素集合 格式为:
* [{"element":"a","score":10.0,"binaryElement":"YQ=="},{"element":"b","score":20.0,"binaryElement":"Yg=="}]
*/
public static Set<Tuple> zrangeWithScores(String key, long start, long end){
Jedis jedis = null;
Set<Tuple> ascResult = null;
try {
jedis = getJedis();
ascResult = jedis.zrangeWithScores(key,start,end);
}finally {
if (jedis != null){
jedis.close();
}
}
return ascResult;
}
/**
* 查询指定索引闭区间的元素(根据分数降序)
* (0,-1表示全部)
* @param key zset的key
* @param start 开始区间
* @param end 结束区间
* @return 元素集合
*/
public static Set<String> zrevrange(String key, long start, long end){
Jedis jedis = null;
Set<String> descResult = null;
try {
jedis = getJedis();
descResult = jedis.zrevrange(key,start,end);
}finally {
if (jedis != null){
jedis.close();
}
}
return descResult;
}
/**
* 查询指定索引闭区间的元素,带着分数(根据分数降序)
* (0,-1表示全部)
* @param key zset的key
* @param start 开始区间
* @param end 结束区间
* @return 元素集合 格式为:
* [{"element":"b","score":20.0,"binaryElement":"Yg=="},{"element":"a","score":10.0,"binaryElement":"YQ=="}]
*/
public static Set<Tuple> zrevrangeWithScores(String key, long start, long end){
Jedis jedis = null;
Set<Tuple> descResult = null;
try {
jedis = getJedis();
descResult = jedis.zrevrangeWithScores(key,start,end);
}finally {
if (jedis != null){
jedis.close();
}
}
return descResult;
}
/**
* 返回有序集合(zset)中的元素个数
* @param key key
* @return 个数
*/
public static Long zcard(String key){
Jedis jedis = null;
Long count = null;
try {
jedis = getJedis();
count = jedis.zcard(key);
}finally {
if (jedis != null){
jedis.close();
}
}
return count;
}
/**
* 返回指定分数区间的元素个数(闭区间)
* @param key key
* @param startScore 开始分数
* @param endScore 结束分数
* @return 个数
*/
public static Long zcount(String key,Long startScore,Long endScore){
Jedis jedis = null;
Long count = null;
try {
jedis = getJedis();
count = jedis.zcount(key,startScore,endScore);
}finally {
if (jedis != null){
jedis.close();
}
}
return count;
}
/**
* 返回某元素在集合中的排名(根据分数降序排列时)
* @param key key
* @param member 集合中的元素
* @return 排名,从0开始
*/
public static Long zrevrank(String key, String member){
Jedis jedis = null;
Long count = null;
try {
jedis = getJedis();
count = jedis.zrevrank(key,member);
}finally {
if (jedis != null){
jedis.close();
}
}
return count;
}
/**
* 返回某元素在集合中的排名(根据分数升序排列时)
* @param key key
* @param member 集合中的元素
* @return 排名,从0开始
*/
public static Long zrank(String key, String member){
Jedis jedis = null;
Long count = null;
try {
jedis = getJedis();
count = jedis.zrank(key,member);
}finally {
if (jedis != null){
jedis.close();
}
}
return count;
}
/**
* 升序查询指定分数闭区间的元素
* @param key key
* @param min 最小分数
* @param max 最大分数
* @return 元素集合
*/
public static Set<String> zrangeByScore(String key,double min, double max){
Jedis jedis = null;
Set<String> members = null;
try {
jedis = getJedis();
members = jedis.zrangeByScore(key, min, max);
}finally {
if (jedis != null){
jedis.close();
}
}
return members;
}
/**
* 升序查询指定分数闭区间的元素,并指定偏移量
* @param key key
* @param min 最小分数
* @param max 最大分数
* @param offset 偏移量
* @param size 数量
* @return 元素集合
*/
public static Set<String> zrangeByScore(String key,double min, double max,int offset,int size){
Jedis jedis = null;
Set<String> members = null;
try {
jedis = getJedis();
members = jedis.zrangeByScore(key, min, max,offset,size);
}finally {
if (jedis != null){
jedis.close();
}
}
return members;
}
/**
* 升序查询指定分数闭区间的元素,带着分数
* @param key key
* @param min 最小分数
* @param max 最大分数
* @return 元素集合
*/
public static Set<Tuple> zrangeByScoreWithScores(String key,double min, double max){
Jedis jedis = null;
Set<Tuple> members = null;
try {
jedis = getJedis();
members = jedis.zrangeByScoreWithScores(key, min, max);
}finally {
if (jedis != null){
jedis.close();
}
}
return members;
}
/**
* 升序查询指定分数闭区间的元素,并指定偏移量,带着分数
* @param key key
* @param min 最小分数
* @param max 最大分数
* @param offset 偏移量
* @param size 数量
* @return 元素集合
*/
public static Set<Tuple> zrangeByScoreWithScores(String key,double min, double max,int offset,int size){
Jedis jedis = null;
Set<Tuple> members = null;
try {
jedis = getJedis();
members = jedis.zrangeByScoreWithScores(key, min, max,offset,size);
}finally {
if (jedis != null){
jedis.close();
}
}
return members;
}
/**
* 降序查询指定分数闭区间的元素
* @param key key
* @param max 最大分数
* @param min 最小分数
* @return 元素集合
*/
public static Set<String> zrevrangebyscore(String key,double max,double min){
Jedis jedis = null;
Set<String> members = null;
try {
jedis = getJedis();
members = jedis.zrevrangeByScore(key, max,min);
}finally {
if (jedis != null){
jedis.close();
}
}
return members;
}
/**
* 降序查询指定分数闭区间的元素,并指定偏移量
* @param key key
* @param max 最大分数
* @param min 最小分数
* @return 元素集合
*/
public static Set<String> zrevrangebyscore(String key,double max,double min,int offset,int size){
Jedis jedis = null;
Set<String> members = null;
try {
jedis = getJedis();
members = jedis.zrevrangeByScore(key, max,min,offset,size);
}finally {
if (jedis != null){
jedis.close();
}
}
return members;
}
/**
* 降序查询指定分数闭区间的元素,并带着分数
* @param key key
* @param min 最小分数
* @param max 最大分数
* @return 元素集合
*/
public static Set<Tuple> zrevrangeByScoreWithScores(String key,double max,double min){
Jedis jedis = null;
Set<Tuple> members = null;
try {
jedis = getJedis();
members = jedis.zrevrangeByScoreWithScores(key,max,min);
}finally {
if (jedis != null){
jedis.close();
}
}
return members;
}
/**
* 降序查询指定分数闭区间的元素,并指定偏移量,带着分数
* @param key key
* @param min 最小分数
* @param max 最大分数
* @param offset 偏移量
* @param size 数量
* @return 元素集合
*/
public static Set<Tuple> zrevrangeByScoreWithScores(String key,double max,double min,int offset,int size){
Jedis jedis = null;
Set<Tuple> members = null;
try {
jedis = getJedis();
members = jedis.zrevrangeByScoreWithScores(key, min, max,offset,size);
}finally {
if (jedis != null){
jedis.close();
}
}
return members;
}
/**
* 有序集合中指定删除一或多个元素
* @param key
* @param member 元素
* @return 删除成功的个数
*/
public static Long zrem(String key, String... member){
Jedis jedis = null;
Long num = null;
try {
jedis = getJedis();
num = jedis.zrem(key,member);
}finally {
if (jedis != null){
jedis.close();
}
}
return num;
}
/**
* 分数升序排名时,删除指定索引区间的元素
* @param key key
* @param start 开始索引
* @param end 结束索引
* @return 删除成功的个数
*/
public static Long zremrangebyrank(String key,long start,long end){
Jedis jedis = null;
Long num = null;
try {
jedis = getJedis();
num = jedis.zremrangeByRank(key,start,end);
}finally {
if (jedis != null){
jedis.close();
}
}
return num;
}
/**
* 分数升序排名时,删除指定分数区间的元素
* @param key key
* @param min 最小分数
* @param max 最大分数
* @return 删除成功的个数
*/
public static Long zremrangeByScore(String key,long min,long max){
Jedis jedis = null;
Long num = null;
try {
jedis = getJedis();
num = jedis.zremrangeByScore(key,min,max);
}finally {
if (jedis != null){
jedis.close();
}
}
return num;
}
/**
* 查询有序集合中某元素的分数
* @param key key
* @param member 元素
* @return 删除成功的个数
*/
public static Double zscore(String key,String member){
Jedis jedis = null;
Double score = null;
try {
jedis = getJedis();
score = jedis.zscore(key,member);
}finally {
if (jedis != null){
jedis.close();
}
}
return score;
}
/**
* 给有序集合中某元素的分数增加(正数)或减少(负数)
* @param key key
* @param score 分数
* @param member 元素
* @return 新的分数
*/
public static Double zincrby(String key,double score,String member){
Jedis jedis = null;
Double newScore = null;
try {
jedis = getJedis();
newScore = jedis.zincrby(key,score,member);
}finally {
if (jedis != null){
jedis.close();
}
}
return newScore;
}
/**
* 私有化构造器,不让实例化对象
*/
private RedisUtils() {
}
public static void main(String[] args) {
JedisPool jedisPool = MyJedisPoolConfig.getJedisPool();
JedisPool jedisPool1 = MyJedisPoolConfig.getJedisPool();
System.out.println(jedisPool == jedisPool1);//true
}
}