概述
Redis(全稱(chēng):Remote Dictionary Server 遠(yuǎn)程字典服務(wù))是一個(gè)開(kāi)源的使用ANSI C語(yǔ)言編寫(xiě)、支持網(wǎng)絡(luò)、可基于內(nèi)存亦可持久化的日志型、Key-Value數(shù)據(jù)庫(kù)、并提供多種語(yǔ)言的API。日常開(kāi)發(fā)中會(huì)經(jīng)常使用到該數(shù)據(jù)庫(kù),在這里記錄一下常用到的方法。
相關(guān)代碼
Maven配置
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
初始化
/**
*Redis配置類(lèi)
*/
@Component
public class DataConfig {
@Value("${redis.ip}")
String ip;
@Value("${redis.port}")
int port;
@Value("${redis.password}")
String password;
@PostConstruct
public void init() {
if(StringUtils.isNotEmpty(password)) {
RedisUtils.init(ip, port, password);
}else {
RedisUtils.init(ip, port);
}
}
}
初始化配置操作
public class RedisUtils {
private static JedisPool pool;
public static JedisPool getPool() {
return pool;
}
//用于判斷當(dāng)前Redis連接是否已經(jīng)初始化
public static boolean isInit;
// 最大空閑連接數(shù)
private static final int MAX_IDLE_COUNT = 500;
// 最大連接數(shù)
private static final int MAX_TOTAL_COUNT = 300;
// 獲取連接時(shí)的最大等待毫秒數(shù)(如果設(shè)置為阻塞時(shí)BlockWhenExhausted),如果超時(shí)就拋異常, 小于零:阻塞不確定的時(shí)間, 默認(rèn)-1
private static final int MAX_WAIT_MILLIS = 5000;
// 默認(rèn)數(shù)據(jù)過(guò)期時(shí)間
public static final int DEFAULT_EXPIRE_SECONDS = 2 * 24 * 60 * 60;
//不過(guò)期的時(shí)間
public static final int FOREVER_EXPIRE_SECONDS = -1;
public static void init(String ip, int port) {
init(ip, port, null, MAX_IDLE_COUNT, MAX_TOTAL_COUNT, MAX_WAIT_MILLIS);
}
public static void init(String ip, int port, String password) {
init(ip, port, password, MAX_IDLE_COUNT, MAX_TOTAL_COUNT, MAX_WAIT_MILLIS);
}
public static void init(String ip, int port, String password, int maxIdleCount, int maxTotalCount,
int maxWaitMillis) {
if (isInit) {
return;
}
isInit = true;
// 建立連接池配置參數(shù)
JedisPoolConfig config = new JedisPoolConfig();
// 最大空閑連接數(shù)
config.setMaxIdle(maxIdleCount);
// 設(shè)置最大阻塞時(shí)間,記住是毫秒數(shù)milliseconds
config.setMaxWaitMillis(maxWaitMillis);
// 最大連接數(shù), 默認(rèn)8個(gè)
config.setMaxTotal(maxTotalCount);
// 創(chuàng)建連接池
if (org.apache.commons.lang3.StringUtils.isEmpty(password)) {
pool = new JedisPool(config, ip, port);
} else {
pool = new JedisPool(config, ip, port, 5000, password);
}
}
/**
* 釋放資源
* @param jedis
*/
private static void closeResource(Jedis jedis) {
try {
jedis.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Key值的常用操作,放在RedisUtils類(lèi)中
/**
* 是否存在指定的key
* @param key
* @return
*/
public static boolean existsKey(String key) {
Jedis jedis = pool.getResource();
try {
return jedis.exists(key);
} catch (Exception e) {
jedis.close();
e.printStackTrace();
} finally {
closeResource(jedis);
}
}
/**
* key表達(dá)式,如:brand_*
* @param keyExpression
* @return
*/
public static Set<String> getKeys(String keyExpression) {
Jedis jedis = pool.getResource();
try {
return jedis.keys(keyExpression);
} catch (Exception e) {
jedis.close();
e.printStackTrace();
return Sets.newHashSet();
} finally {
closeResource(jedis);
}
}
/**
* 移除指定的key
* @param key
*/
public static void delKey(String key) {
Jedis jedis = pool.getResource();
try {
jedis.del(key);
} catch (Exception e) {
jedis.close();
Logger.error(e.getMessage(), e);
} finally {
closeResource(jedis);
}
}
/**
* 單獨(dú)設(shè)置指定key的過(guò)期時(shí)間
* @param key-key
* @param expireSeconds--過(guò)期時(shí)間(秒)
*/
public static void setKeyExpireTime(String key, int expireSeconds) {
if (expireSeconds <= 0) {
return;
}
Jedis jedis = pool.getResource();
try {
jedis.expire(key, expireSeconds);
} catch (Exception e) {
jedis.close();
Logger.error(e.getMessage(), e);
} finally {
closeResource(jedis);
}
}
Incr 命令
Redis Incr 命令將 key 中儲(chǔ)存的數(shù)字值增一。
如果 key 不存在,那么 key 的值會(huì)先被初始化為 0 ,然后再執(zhí)行 INCR 操作。
如果值包含錯(cuò)誤的類(lèi)型,或字符串類(lèi)型的值不能表示為數(shù)字,那么返回一個(gè)錯(cuò)誤。
本操作的值限制在 64 位(bit)有符號(hào)數(shù)字表示之內(nèi)。
/**
* 獲取自增id
*
* @param key-key
* @return
*/
public static int getAutoIncreaseId(String key) {
Jedis jedis = pool.getResource();
try {
return jedis.incr(key).intValue();
} catch (Exception e) {
Logger.error(e.getMessage(), e);
return -1;
} finally {
closeResource(jedis);
}
}
/**
* 將key中儲(chǔ)存的數(shù)字值增1
* @param key -key
* @return
*/
public static long incr(String key, int expireSeconds) {
Jedis jedis = pool.getResource();
try {
// 當(dāng) key 不存在時(shí),返回 -2 。
// 當(dāng) key 存在但沒(méi)有設(shè)置剩余生存時(shí)間時(shí),返回 -1 。
// 否則,以毫秒為單位,返回 key 的剩余生存時(shí)間。
long ttl = jedis.ttl(key);
if (ttl > 0) {
return jedis.incr(key);
} else if (ttl < 0) {
Long incr = jedis.incr(key);
jedis.expire(key, expireSeconds);
return incr;
}
return -1;
} catch (Exception e) {
Logger.error(e.getMessage(), e);
return -1;
} finally {
closeResource(jedis);
}
}
/**
* 將key中儲(chǔ)存的數(shù)字值增1
* @param key -key
* @return
*/
public static long incr(String key) {
Jedis jedis = pool.getResource();
try {
Long incr = jedis.incr(key);
return incr;
} catch (Exception e) {
Logger.error(e.getMessage(), e);
return -1;
} finally {
closeResource(jedis);
}
}
/**
* 自減操作
*/
public static int getAutoDecrement(String key) {
Jedis jedis = pool.getResource();
try {
return jedis.decr(key).intValue();
} catch (Exception e) {
// Logger.error(e.getMessage(), e);
e.printStackTrace();
return -1;
} finally {
closeResource(jedis);
}
}
根據(jù)Key查詢(xún)/寫(xiě)入值或?qū)ο?/h4>
/**
* 從緩存獲取指定key的對(duì)象
*
* @param key
* @param c
* @return
*/
public static <T> T getValue(String key, Class<T> c) {
String s = getValue(key);
if (StringUtils.isEmpty(s)) {
return null;
}
return gson.fromJson(s, c);
}
/**
* 從緩存批量獲取keys的對(duì)象集合
* @param keys
* @param c
* @param <T>
* @return
*/
public static <T> List<T> getValues(String[] keys, Class<T> c) {
Jedis jedis = pool.getResource();
List<T> list = new ArrayList<T>();
try {
List<String> results = jedis.mget(keys);
for (String s : results) {
if (!StringUtils.isEmpty(s)) {
list.add(JSONObject.parseObject(s, c));
}
}
} catch (Exception e) {
jedis.close();
e.printStackTrace();
} finally {
closeResource(jedis);
}
return list;
}
/**
* 從緩存取得指定key的字符串<br/>
* 該方法不對(duì)外提供,以免與T參數(shù)方法誤用
*
* @param key
* @return
*/
private static String getValue(String key) {
Jedis jedis = pool.getResource();
try {
String s = jedis.get(key);
return s == null ? "" : s;
} catch (Exception e) {
jedis.close();
e.printStackTrace();
return "";
} finally {
closeResource(jedis);
}
}
/**
* 保存單個(gè)對(duì)象(如果對(duì)象已經(jīng)存在,則覆蓋)<br/>
* 默認(rèn)過(guò)期時(shí)間:3天
*
* @param key
* @param value
*/
public static <T> void setValue(String key, T value) {
setValue(key, value, DEFAULT_EXPIRE_SECONDS);
}
/**
* 保存單個(gè)對(duì)象(如果對(duì)象已經(jīng)存在,則覆蓋)<br/>
*
* @param key
* @param value
* @param expireSeconds-過(guò)期時(shí)間(秒)
*/
public static <T> void setValue(String key, T value, int expireSeconds) {
if (value != null) {
setValue(key, value, expireSeconds, false);
}
}
/**
* 保存單個(gè)對(duì)象(如果對(duì)象已經(jīng)存在,則覆蓋)-包括flag
* @param key
* @param value
* @param expireSeconds
* @param needSetFlag
* @param <T>
*/
public static <T> void setValue(String key, T value, int expireSeconds, boolean needSetFlag) {
if (value != null) {
setValue(key, JSONObject.toJSONString(value), expireSeconds, needSetFlag);
// setValue(key, gson.toJson(value), expireSeconds, needSetFlag);
}
}
/**
* 保存字符串(如果對(duì)象已經(jīng)存在,則覆蓋)
*
* @param key-key
* @param value-value
* @param expireTime-過(guò)期時(shí)間,類(lèi)型:yyyy-MM-dd
* HH:mm:ss
*/
public static <T> void setValue(String key, T value, String expireTime) {
if (value != null) {
long toTime = FastDateUtils.getTime(expireTime, FastDateFormat.DATE_TIME);
int expireSeconds = (int) (toTime - System.currentTimeMillis()) / 1000;
if (expireSeconds > 0) {
setValue(key, value, expireSeconds);
}
}
}
/**
* 保存字符串(如果對(duì)象已經(jīng)存在,則覆蓋)
* @param key
* @param value
* @param expireSeconds
* @param needSetFlag
*/
private static void setValue(String key, String value, int expireSeconds, boolean needSetFlag) {
Jedis jedis = pool.getResource();
try {
if (expireSeconds > 0) {
jedis.set(key, value);
jedis.expire(key, expireSeconds);
} else {// 不設(shè)置過(guò)期時(shí)間則需檢測(cè)之前是否設(shè)置有過(guò)期時(shí)間,有則需設(shè)置回原有的過(guò)期時(shí)間
// 獲取key過(guò)期時(shí)間,因?yàn)閟et后原有的key過(guò)期時(shí)間將被清空
long expireTime = jedis.pttl(key);// 剩余過(guò)期毫秒數(shù)
jedis.set(key, value);
if (expireTime > 0) {
int time = (int) Math.ceil((float) expireTime / 1000);
jedis.expire(key, time);// 再設(shè)置原有剩余秒數(shù) 向上取整,如2.1 則為3
}
}
} catch (Exception e) {
jedis.close();
e.printStackTrace();
throw new RedisException(e.getMessage(), e);
} finally {
closeResource(jedis);
}
}
setnx命令操作
將 key 的值設(shè)為 value ,當(dāng)且僅當(dāng) key 不存在。
若給定的 key 已經(jīng)存在,則 SETNX 不做任何動(dòng)作。
SETNX 是『SET if Not eXists』(如果不存在,則 SET)的簡(jiǎn)寫(xiě)。
/**
* 保存對(duì)象(如果不存在key的話)
*
* @param key
* @param value
* @return 不存在key,則保存成功,返回true,存在key,則保存失敗,返回false
*/
public static <T> boolean setnxWithNoExpire(String key, T value) {
return setnx(key, value, 0);
}
/**
* 保存對(duì)象(如果不存在key的話)
*
* @param key
* @param value
* @return 不存在key,則保存成功,返回true,存在key,則保存失敗,返回false
*/
public static <T> boolean setnx(String key, T value, int expireSeconds) {
return setnx(key, JSONObject.toJSONString(value), expireSeconds);
}
/**
* 保存字符串(如果不存在key的話)
*
* @param key
* @param value
* @return 不存在key,則保存成功,返回true,存在key,則保存失敗,返回false
*/
private static boolean setnx(String key, String value, int expireSeconds) {
Jedis jedis = pool.getResource();
try {
// 1 if the key was set 0 if the key was not set
boolean setnxOK = jedis.setnx(key, value) == 1;
// 設(shè)置過(guò)期時(shí)間
if (expireSeconds > 0) {
if (setnxOK) { // 設(shè)置成功了,則設(shè)置失效時(shí)間
jedis.expire(key, expireSeconds);
} else if (!setnxOK && jedis.pttl(key) < 0) {// 或者由于某些異常狀態(tài)setnx執(zhí)行成功
// 但expire沒(méi)有成功,可能會(huì)導(dǎo)致鎖永遠(yuǎn)釋放不掉,這里強(qiáng)制設(shè)置過(guò)期時(shí)間
jedis.expire(key, expireSeconds);
}
}
if (setnxOK) {
return true;
}
} catch (Exception e) {
jedis.close();
e.printStackTrace();
} finally {
closeResource(jedis);
}
return false;
}
List操作
/**
* 設(shè)置一個(gè)全新的list<br/>
* 如果之前已經(jīng)存在key,則會(huì)先移除,再添加
*
* @param key
* @param list
*/
public static <T> void setList(String key, List<T> list) {
if (list == null || list.size() == 0) {
return;
}
Jedis jedis = pool.getResource();
try {
String[] ss = new String[list.size()];
for (int i = 0; i < list.size(); i++) {
ss[i] = JSONObject.toJSONString(list.get(i));
}
delKey(key);// 先移除之前的key,再新增
jedis.rpush(key, ss);
} catch (Exception e) {
jedis.close();
e.printStackTrace();
throw new RedisException(e.getMessage(), e);
} finally {
closeResource(jedis);
}
}
/**
*
* @param key
* @param list
* @param timeOut
* @param <T>
*/
public static <T> void setList(String key, List<T> list,Integer timeOut) {
if (list == null || list.size() == 0) {
return;
}
Jedis jedis = pool.getResource();
try {
String[] ss = new String[list.size()];
for (int i = 0; i < list.size(); i++) {
ss[i] = JSONObject.toJSONString(list.get(i));
}
jedis.rpush(key, ss);
jedis.expire(key,timeOut);
} catch (Exception e) {
jedis.close();
e.printStackTrace();
throw new RedisException(e.getMessage(), e);
} finally {
closeResource(jedis);
}
}
/**
* 添加一個(gè)value到原有列表到尾部
* @param key
* @param value
* @param <T>
*/
public static <T> void addList(String key, T value) {
Jedis jedis = pool.getResource();
try {
String[] ss = new String[1];
ss[0] = JSONObject.toJSONString(value);
jedis.rpush(key, ss);
} catch (Exception e) {
jedis.close();
e.printStackTrace();
throw new RedisException(e.getMessage(), e);
} finally {
closeResource(jedis);
}
}
/**
* 添加一個(gè)value到原有列表頭部
*
* @param key
* @param value
*/
public static <T> void addListToHead(String key, T value) {
Jedis jedis = pool.getResource();
try {
String[] ss = new String[1];
ss[0] = JSONObject.toJSONString(value);
jedis.lpush(key, JSONObject.toJSONString(value));
} catch (Exception e) {
jedis.close();
e.printStackTrace();
throw new RedisException(e.getMessage(), e);
} finally {
closeResource(jedis);
}
}
/**
* 設(shè)置list中指定索引的值
*
* @param key
* @param index-索引
* @param value
*/
public static <T> void setListElement(String key, int index, T value) {
Jedis jedis = pool.getResource();
try {
jedis.lset(key, index, JSONObject.toJSONString(value));
} catch (Exception e) {
jedis.close();
e.printStackTrace();
throw new RedisException(e.getMessage(), e);
} finally {
closeResource(jedis);
}
}
/**
* 返回某個(gè)范圍內(nèi)的集合,無(wú)結(jié)果集則返回空l(shuí)ist
*
* @param key
* @param start-起始索引(包含,從0開(kāi)始)
* @param end-結(jié)束索引(包含)
* @return
*/
private static List<String> getListRange(String key, int start, int end) {
Jedis jedis = pool.getResource();
try {
return jedis.lrange(key, start, end);
} catch (Exception e) {
jedis.close();
e.printStackTrace();
return null;
} finally {
closeResource(jedis);
}
}
/**
* 返回某個(gè)范圍內(nèi)的集合,無(wú)結(jié)果集則返回空l(shuí)ist
*
* @param key
* @param start-起始索引(包含,從0開(kāi)始)
* @param end-結(jié)束索引(包含)
* @param c-具體類(lèi)
* @return
*/
public static <T> List<T> getListRange(String key, int start, int end, Class<T> c) {
List<String> slist = getListRange(key, start, end);
List<T> list = new ArrayList<T>();
for (String s : slist) {
list.add(gson.fromJson(s, c));
}
return list.isEmpty() ? null : list;
}
/**
* 分頁(yè)獲取list
*
* @param key
* @param pageNow-當(dāng)前頁(yè)數(shù)
* @param pageSize-每頁(yè)記錄數(shù)
* @param c
* @return
*/
public static <T> List<T> getListPage(String key, int pageNow, int pageSize, Class<T> c) {
int startIndex = (pageNow - 1) * pageSize;
int endIndex = pageNow * pageSize - 1;
return getListRange(key, startIndex, endIndex, c);
}
/**
* 獲取指定key下的列表所有記錄
*
* @param key
* @param c
* @return
*/
public static <T> List<T> getAllList(String key, Class<T> c) {
return getListRange(key, 0, -1, c);
}
/**
* 獲取列表第一個(gè)元素
*
* @param key
* @param c
* @return
*/
public static <T> T getListFirstElement(String key, Class<T> c) {
Jedis jedis = pool.getResource();
try {
return JSONObject.parseObject(jedis.lindex(key, 0), c);
} catch (Exception e) {
jedis.close();
e.printStackTrace();
return null;
} finally {
closeResource(jedis);
}
}
/**
* 返回并刪除list中的首元素
*
* @param key
* @return
*/
public static <T> T getListPop(String key, Class<T> c) {
Jedis jedis = pool.getResource();
try {
return JSONObject.parseObject(jedis.lpop(key), c);
} catch (Exception e) {
jedis.close();
e.printStackTrace();
return null;
} finally {
closeResource(jedis);
}
}
/**
* 獲取列表最后一個(gè)元素
*
* @param key
* @param c
* @return
*/
public static <T> T getListLastElement(String key, Class<T> c) {
Jedis jedis = pool.getResource();
try {
return JSONObject.parseObject(jedis.lindex(key, -1), c);
} catch (Exception e) {
jedis.close();
e.printStackTrace();
return null;
} finally {
closeResource(jedis);
}
}
/**
* 返回list的集合個(gè)數(shù)
*
* @param key
* @return
*/
public static int getListSize(String key) {
Jedis jedis = pool.getResource();
try {
return jedis.llen(key).intValue();
} catch (Exception e) {
jedis.close();
e.printStackTrace();
return 0;
} finally {
closeResource(jedis);
}
}
/**
* 刪除list的指定對(duì)象
*
* @param key
* @param values
*/
@SuppressWarnings("unchecked")
public static <T> void removeValueFromList(String key, T... values) {
Jedis jedis = pool.getResource();
try {
for (T v : values) {
jedis.lrem(key, 0, JSONObject.toJSONString(v));
}
} catch (Exception e) {
jedis.close();
e.printStackTrace();
throw new RedisException(e.getMessage(), e);
} finally {
closeResource(jedis);
}
}
/**
* 刪除一個(gè)列表
*
* @param key
*/
public static void removeList(String key) {
Jedis jedis = pool.getResource();
try {
if (jedis.llen(key) > 0) {
jedis.ltrim(key, 1, 0);
}
} catch (Exception e) {
jedis.close();
e.printStackTrace();
throw new RedisException(e.getMessage(), e);
} finally {
closeResource(jedis);
}
}
Map操作
/**
* 保存Java map to Redis map
* @param hashKey
* @param map
*/
public static <T> void addToHashMap(String hashKey, Map<String, T> map) {
if (map == null || map.isEmpty()) {
return;
}
Jedis jedis = pool.getResource();
try {
for (String key : map.keySet()) {
String value = JSONObject.toJSONString(map.get(key));
jedis.hset(hashKey, key, value);
}
jedis.expire(hashKey, DEFAULT_EXPIRE_SECONDS);
} catch (Exception e) {
jedis.close();
e.printStackTrace();
throw new RedisException(e.getMessage(), e);
} finally {
closeResource(jedis);
}
}
/**
* 保存Java map to Redis map
*
* @param hashKey
* @param map
*/
public static <K, V> void addToHashMap2(String hashKey, Map<K, V> map) {
if (map == null || map.isEmpty()) {
return;
}
Jedis jedis = pool.getResource();
try {
for (K key : map.keySet()) {
String value = JSONObject.toJSONString(map.get(key));
jedis.hset(hashKey, String.valueOf(key), value);
}
} catch (Exception e) {
jedis.close();
e.printStackTrace();
throw new RedisException(e.getMessage(), e);
} finally {
closeResource(jedis);
}
}
/**
* 保存Java value to Redis map
*
* @param hashKey
* @param key
* @param value
*/
public static <T> void addToHashMap(String hashKey, String key, T value) {
Jedis jedis = pool.getResource();
try {
jedis.hset(hashKey, key, JSONObject.toJSONString(value));
} catch (Exception e) {
jedis.close();
e.printStackTrace();
throw new RedisException(e.getMessage(), e);
} finally {
closeResource(jedis);
}
}
/**
* 從hashmap中返回某個(gè)key的值
*
* @param hashKey
* @param key
* @param c-類(lèi)型
* @return
*/
public static <T> T getValueFromHashMap(String hashKey, String key, Class<T> c) {
Jedis jedis = pool.getResource();
try {
String s = jedis.hget(hashKey, key);
if (StringUtils.isEmpty(s)) {
return null;
}
return JSONObject.parseObject(s, c);
} catch (Exception e) {
jedis.close();
e.printStackTrace();
return null;
} finally {
closeResource(jedis);
}
}
/**
* 從hashmap中返回某個(gè)key的值
* @param hashKey
* @param key
* @param typeOfT
* @param <T>
* @return
*/
public static <T> T getValueFromHashMap(String hashKey, String key, Type typeOfT) {
Jedis jedis = pool.getResource();
try {
String s = jedis.hget(hashKey, key);
if (StringUtils.isEmpty(s)) {
return null;
}
return JSONObject.parseObject(s, typeOfT);
} catch (Exception e) {
jedis.close();
e.printStackTrace();
return null;
} finally {
closeResource(jedis);
}
}
/**
* 返回整個(gè)map對(duì)象
*
* @param hashKey
* @return
*/
public static <T> Map<String, T> getAllFromHashMap(String hashKey, Class<T> c) {
Jedis jedis = pool.getResource();
try {
Map<String, String> map = jedis.hgetAll(hashKey);
Map<String, T> tMap = new HashMap<String, T>(map.size());
for (String key : map.keySet()) {
T value = JSONObject.parseObject(map.get(key), c);
tMap.put(key, value);
}
return tMap;
} catch (Exception e) {
jedis.close();
e.printStackTrace();
return null;
} finally {
closeResource(jedis);
}
}
/**
* 獲取hashmap的size
*
* @param hashKey
* @return
*/
public static long getSizeFromHashMap(String hashKey) {
Jedis jedis = pool.getResource();
try {
return jedis.hlen(hashKey);
} catch (Exception e) {
jedis.close();
e.printStackTrace();
return 0;
} finally {
closeResource(jedis);
}
}
/**
* 刪除map中的指定key
*
* @param hashKey
* @param keys
*/
public static void removeFromHashMap(String hashKey, String... keys) {
Jedis jedis = pool.getResource();
try {
jedis.hdel(hashKey, keys);
} catch (Exception e) {
jedis.close();
e.printStackTrace();
} finally {
closeResource(jedis);
}
}
/**
* 獲取某個(gè)Map的所有key集合
*
* @param hashKey
* @return
*/
public static Set<String> getKeysFromHashMap(String hashKey) {
Jedis jedis = pool.getResource();
try {
return jedis.hkeys(hashKey);
} catch (Exception e) {
jedis.close();
e.printStackTrace();
return null;
} finally {
closeResource(jedis);
}
}
/**
* 刪除某Map所有的元素
*
* @param hashKey
*/
public static void removeHashMap(String hashKey) {
if (StringUtils.isEmpty(hashKey)) {
return;
}
Set<String> keySet = getKeysFromHashMap(hashKey);
if (keySet == null || keySet.isEmpty()) {
return;
}
// 化成數(shù)組
String[] keyArr = keySet.toArray(new String[] {});
if (keyArr == null || keyArr.length == 0) {
return;
}
// 批量刪除
removeFromHashMap(hashKey, keyArr);
}
/**
* 在hashmap中是否存在指定的key
* @param hashKey
* @param key
* @return
*/
public static boolean hasKeyFromHashMap(String hashKey, String key) {
Jedis jedis = pool.getResource();
try {
return jedis.hexists(hashKey, key);
} catch (Exception e) {
jedis.close();
e.printStackTrace();
return false;
} finally {
closeResource(jedis);
}
}
zSet操作
Redis 有序集合和集合一樣也是string類(lèi)型元素的集合,且不允許重復(fù)的成員。
不同的是每個(gè)元素都會(huì)關(guān)聯(lián)一個(gè)double類(lèi)型的分?jǐn)?shù)。redis正是通過(guò)分?jǐn)?shù)來(lái)為集合中的成員進(jìn)行從小到大的排序。
有序集合的成員是唯一的,但分?jǐn)?shù)(score)卻可以重復(fù)。
集合是通過(guò)哈希表實(shí)現(xiàn)的,所以添加,刪除,查找的復(fù)雜度都是O(1)。 集合中最大的成員數(shù)為 232 - 1 (4294967295, 每個(gè)集合可存儲(chǔ)40多億個(gè)成員)。
/**
* 寫(xiě)入zset隊(duì)列
* @param key
* @param map
* @return
*/
public static boolean setZsetValue(String key, Map<String, Double> map) {
if (StringUtils.isEmpty(key)) {
return false;
}
if(map == null || map.size() <= 0) {
return false;
}
Jedis jedis = pool.getResource();
try {
Long count = jedis.zadd(key, map);
if(count > 0) {
return true;
}
} catch (Exception e) {
closeResource(jedis);
Logger.error("RedisClient->setZsetValue插入隊(duì)列失敗 map=[" + JSONObject.toJSONString(map) + "]", e);
} finally {
closeResource(jedis);
}
return false;
}
/**
* 根據(jù)范圍返回zSet隊(duì)列任務(wù)
* @param key
* @param minIndex
* @param maxIndex
* @return
*/
public static Set<String> getZsetValuesByRange(String key, int minIndex, int maxIndex) {
Set<String> set = Collections.emptySet();
if(existsKey(key)) {
if(getZsetCount(key) <= 0) {
return set;
}
Jedis jedis = pool.getResource();
try {
set = jedis.zrange(key, minIndex, maxIndex);
return set;
} catch (Exception e) {
closeResource(jedis);
Logger.error("RedisClient->getZsetValuesByRange獲取隊(duì)列任務(wù)失敗 key=[" + key + "], index=["+minIndex+","+maxIndex+"]", e);
} finally {
closeResource(jedis);
}
}
return set;
}
/**
* 根據(jù)Value刪除指定Zset隊(duì)列元素
* @param key
* @param value
* @return
*/
public static boolean remZsetValue(String key, String value) {
if (StringUtils.isEmpty(key)) {
return false;
}
if(existsKey(key)) {
Jedis jedis = pool.getResource();
try {
Long count = jedis.zrem(key, value);
if(count > 0) {
return true;
}
} catch (Exception e) {
closeResource(jedis);
Logger.error("RedisClient->remZsetValue刪除隊(duì)列任務(wù)失敗 key=[" + key + "], value=["+value+"]", e);
return false;
} finally {
closeResource(jedis);
}
}
return false;
}
public static long getZsetCount(String key) {
if (StringUtils.isEmpty(key)) {
return 0;
}
if(existsKey(key)) {
Jedis jedis = pool.getResource();
try {
return jedis.zcard(key);
} catch (Exception e) {
closeResource(jedis);
e.printStackTrace();
return 0;
} finally {
closeResource(jedis);
}
}
return 0;
}
Redis Hincrby 命令
Redis Hincrby 命令用于為哈希表中的字段值加上指定增量值。
增量也可以為負(fù)數(shù),相當(dāng)于對(duì)指定字段進(jìn)行減法操作。
如果哈希表的 key 不存在,一個(gè)新的哈希表被創(chuàng)建并執(zhí)行 HINCRBY 命令。
如果指定的字段不存在,那么在執(zhí)行命令前,字段的值被初始化為 0 。
對(duì)一個(gè)儲(chǔ)存字符串值的字段執(zhí)行 HINCRBY 命令將造成一個(gè)錯(cuò)誤。
本操作的值被限制在 64 位(bit)有符號(hào)數(shù)字表示之內(nèi)。
/**
* 為哈希表 key 中的域 field 的值加1
* @param key
* @param field
* @return
*/
public static long incrementHashMapValue(String key, String field) {
return incrementHashMapValue(key, field, 1);
}
/**
* 為哈希表 key 中的域 field 的值減1
* @param key
* @param field
* @return
*/
public static long decrementHashMapValue(String key, String field) {
return incrementHashMapValue(key, field, -1);
}
public static long incrementHashMapValue(String key, String field, long increment) {
Jedis jedis = pool.getResource();
try {
return jedis.hincrBy(key, field, increment);
} catch (Exception e) {
// Logger.error(e.getMessage(), e);
e.printStackTrace();
return -1;
} finally {
closeResource(jedis);
}
}
Set集合(無(wú)序列表)操作
/**
* 添加set集合
*/
public static void addSetValue(String key, String value, int expireSeconds) {
Jedis jedis = pool.getResource();
try {
if (expireSeconds > 0) {
jedis.sadd(key, value);
jedis.expire(key, expireSeconds);
} else {// 不設(shè)置過(guò)期時(shí)間則需檢測(cè)之前是否設(shè)置有過(guò)期時(shí)間,有則需設(shè)置回原有的過(guò)期時(shí)間
// 獲取key過(guò)期時(shí)間,因?yàn)閟et后原有的key過(guò)期時(shí)間將被清空
long expireTime = jedis.pttl(key);// 剩余過(guò)期毫秒數(shù)
jedis.sadd(key, value);
if (expireTime > 0) {
int time = (int) Math.ceil((float) expireTime / 1000);
jedis.expire(key, time);// 再設(shè)置原有剩余秒數(shù) 向上取整,如2.1 則為3
}
}
} catch (Exception e) {
jedis.close();
e.printStackTrace();
throw new RedisException(e.getMessage(), e);
} finally {
closeResource(jedis);
}
}
/**
* 批量-添加set集合
*/
public static void addSetValue(String key, String[] value, int expireSeconds) {
Jedis jedis = pool.getResource();
try {
if (expireSeconds > 0) {
jedis.sadd(key, value);
jedis.expire(key, expireSeconds);
} else {// 不設(shè)置過(guò)期時(shí)間則需檢測(cè)之前是否設(shè)置有過(guò)期時(shí)間,有則需設(shè)置回原有的過(guò)期時(shí)間
// 獲取key過(guò)期時(shí)間,因?yàn)閟et后原有的key過(guò)期時(shí)間將被清空
long expireTime = jedis.pttl(key);// 剩余過(guò)期毫秒數(shù)
jedis.sadd(key, value);
if (expireTime > 0) {
int time = (int) Math.ceil((float) expireTime / 1000);
jedis.expire(key, time);// 再設(shè)置原有剩余秒數(shù) 向上取整,如2.1 則為3
}
}
} catch (Exception e) {
jedis.close();
e.printStackTrace();
throw new RedisException(e.getMessage(), e);
} finally {
closeResource(jedis);
}
}
/**
* 移除集合中一個(gè)或多個(gè)成員
* @param key
* @param members
* @return
*/
public static boolean delSetValues(String key, String... members){
Jedis jedis = null;
try {
jedis = pool.getResource();
Long value = jedis.srem(key, members);
if(value > 0){
return true;
}
}catch (Exception e) {
e.printStackTrace();
}finally{
if(jedis != null){
jedis.close();
}
}
return false;
}
/**
* 獲取set集合
*/
public static Set<String> getSetValue(String key) {
Jedis jedis = pool.getResource();
try {
return jedis.smembers(key);
} catch (Exception e) {
jedis.close();
e.printStackTrace();
return Sets.newHashSet();
} finally {
closeResource(jedis);
}
}
/**
* 獲取對(duì)象轉(zhuǎn)換的Set集合
* @param key
* @param c
* @param <T>
* @return
*/
public static <T> Set<T> getSetValue(String key, Class<T> c) {
Set<String> set = getSetValue(key);
Set<T> temp = new HashSet<>();
if(set.size() > 0){
for (String s : set) {
temp.add(JSONObject.parseObject(s, c));
}
}
return temp;
}
/**
* 彈出Set集合
* @param sourceKey
* @param targetKey
* @return
*/
public static Set<String> moveSetValue(String sourceKey, String targetKey){
Jedis jedis = pool.getResource();
try {
//獲取當(dāng)前列表元素
Set<String> currentSet = jedis.smembers(sourceKey);
if(currentSet.size() <= 0){
return Sets.newHashSet();
}
//將元素移到另外一個(gè)集合
for (String value :currentSet){
jedis.smove(sourceKey, targetKey, value);
}
Set<String> set = jedis.smembers(targetKey);
return set;
} catch (Exception e) {
jedis.close();
e.printStackTrace();
return Sets.newHashSet();
} finally {
closeResource(jedis);
}
}
/**
* 彈出Set對(duì)象集合
* @param sourceKey
* @param targetKey
* @param c
* @param <T>
* @return
*/
public static <T> Set<T> moveSetValue(String sourceKey, String targetKey, Class<T> c) {
Set<String> set = moveSetValue(sourceKey, targetKey);
Set<T> temp = new HashSet<>();
if(set.size() > 0){
for (String s : set) {
temp.add(JSONObject.parseObject(s, c));
}
}
return temp;
}
/**
* 獲取Set集合總數(shù)
* @param key
* @return
*/
public static long getSetCount(String key) {
Jedis jedis = pool.getResource();
try {
return jedis.scard(key);
} catch (Exception e) {
jedis.close();
e.printStackTrace();
return BasicDataUtil.DEFAULT_LONG;
} finally {
closeResource(jedis);
}
}
/**
* 查詢(xún)set集合內(nèi)是否存在該元素
* @param key
* @param val
* @return
*/
public static Boolean existsKeyInSet(String key, String val) {
Jedis jedis = pool.getResource();
try {
return jedis.sismember(key, val);
} catch (Exception e) {
jedis.close();
e.printStackTrace();
return Boolean.FALSE;
} finally {
closeResource(jedis);
}
}
/**
* 從set集合中彈出一定數(shù)量的元素(數(shù)量由傳入?yún)?shù)控制)
*/
public static Set<String> getSetValueBySpop(String key, long count){
Jedis jedis = pool.getResource();
Set<String> value;
try {
value = jedis.spop(key,count);
}catch (Exception e) {
jedis.close();
e.printStackTrace();
return new HashSet<>();
} finally {
closeResource(jedis);
}
return value;
}
/**
* 從緩存獲取指定key的對(duì)象
*
* @param key
* @param c
* @return
*/
public static <T> T getValue(String key, Class<T> c) {
String s = getValue(key);
if (StringUtils.isEmpty(s)) {
return null;
}
return gson.fromJson(s, c);
}
/**
* 從緩存批量獲取keys的對(duì)象集合
* @param keys
* @param c
* @param <T>
* @return
*/
public static <T> List<T> getValues(String[] keys, Class<T> c) {
Jedis jedis = pool.getResource();
List<T> list = new ArrayList<T>();
try {
List<String> results = jedis.mget(keys);
for (String s : results) {
if (!StringUtils.isEmpty(s)) {
list.add(JSONObject.parseObject(s, c));
}
}
} catch (Exception e) {
jedis.close();
e.printStackTrace();
} finally {
closeResource(jedis);
}
return list;
}
/**
* 從緩存取得指定key的字符串<br/>
* 該方法不對(duì)外提供,以免與T參數(shù)方法誤用
*
* @param key
* @return
*/
private static String getValue(String key) {
Jedis jedis = pool.getResource();
try {
String s = jedis.get(key);
return s == null ? "" : s;
} catch (Exception e) {
jedis.close();
e.printStackTrace();
return "";
} finally {
closeResource(jedis);
}
}
/**
* 保存單個(gè)對(duì)象(如果對(duì)象已經(jīng)存在,則覆蓋)<br/>
* 默認(rèn)過(guò)期時(shí)間:3天
*
* @param key
* @param value
*/
public static <T> void setValue(String key, T value) {
setValue(key, value, DEFAULT_EXPIRE_SECONDS);
}
/**
* 保存單個(gè)對(duì)象(如果對(duì)象已經(jīng)存在,則覆蓋)<br/>
*
* @param key
* @param value
* @param expireSeconds-過(guò)期時(shí)間(秒)
*/
public static <T> void setValue(String key, T value, int expireSeconds) {
if (value != null) {
setValue(key, value, expireSeconds, false);
}
}
/**
* 保存單個(gè)對(duì)象(如果對(duì)象已經(jīng)存在,則覆蓋)-包括flag
* @param key
* @param value
* @param expireSeconds
* @param needSetFlag
* @param <T>
*/
public static <T> void setValue(String key, T value, int expireSeconds, boolean needSetFlag) {
if (value != null) {
setValue(key, JSONObject.toJSONString(value), expireSeconds, needSetFlag);
// setValue(key, gson.toJson(value), expireSeconds, needSetFlag);
}
}
/**
* 保存字符串(如果對(duì)象已經(jīng)存在,則覆蓋)
*
* @param key-key
* @param value-value
* @param expireTime-過(guò)期時(shí)間,類(lèi)型:yyyy-MM-dd
* HH:mm:ss
*/
public static <T> void setValue(String key, T value, String expireTime) {
if (value != null) {
long toTime = FastDateUtils.getTime(expireTime, FastDateFormat.DATE_TIME);
int expireSeconds = (int) (toTime - System.currentTimeMillis()) / 1000;
if (expireSeconds > 0) {
setValue(key, value, expireSeconds);
}
}
}
/**
* 保存字符串(如果對(duì)象已經(jīng)存在,則覆蓋)
* @param key
* @param value
* @param expireSeconds
* @param needSetFlag
*/
private static void setValue(String key, String value, int expireSeconds, boolean needSetFlag) {
Jedis jedis = pool.getResource();
try {
if (expireSeconds > 0) {
jedis.set(key, value);
jedis.expire(key, expireSeconds);
} else {// 不設(shè)置過(guò)期時(shí)間則需檢測(cè)之前是否設(shè)置有過(guò)期時(shí)間,有則需設(shè)置回原有的過(guò)期時(shí)間
// 獲取key過(guò)期時(shí)間,因?yàn)閟et后原有的key過(guò)期時(shí)間將被清空
long expireTime = jedis.pttl(key);// 剩余過(guò)期毫秒數(shù)
jedis.set(key, value);
if (expireTime > 0) {
int time = (int) Math.ceil((float) expireTime / 1000);
jedis.expire(key, time);// 再設(shè)置原有剩余秒數(shù) 向上取整,如2.1 則為3
}
}
} catch (Exception e) {
jedis.close();
e.printStackTrace();
throw new RedisException(e.getMessage(), e);
} finally {
closeResource(jedis);
}
}
將 key 的值設(shè)為 value ,當(dāng)且僅當(dāng) key 不存在。
若給定的 key 已經(jīng)存在,則 SETNX 不做任何動(dòng)作。
SETNX 是『SET if Not eXists』(如果不存在,則 SET)的簡(jiǎn)寫(xiě)。
/**
* 保存對(duì)象(如果不存在key的話)
*
* @param key
* @param value
* @return 不存在key,則保存成功,返回true,存在key,則保存失敗,返回false
*/
public static <T> boolean setnxWithNoExpire(String key, T value) {
return setnx(key, value, 0);
}
/**
* 保存對(duì)象(如果不存在key的話)
*
* @param key
* @param value
* @return 不存在key,則保存成功,返回true,存在key,則保存失敗,返回false
*/
public static <T> boolean setnx(String key, T value, int expireSeconds) {
return setnx(key, JSONObject.toJSONString(value), expireSeconds);
}
/**
* 保存字符串(如果不存在key的話)
*
* @param key
* @param value
* @return 不存在key,則保存成功,返回true,存在key,則保存失敗,返回false
*/
private static boolean setnx(String key, String value, int expireSeconds) {
Jedis jedis = pool.getResource();
try {
// 1 if the key was set 0 if the key was not set
boolean setnxOK = jedis.setnx(key, value) == 1;
// 設(shè)置過(guò)期時(shí)間
if (expireSeconds > 0) {
if (setnxOK) { // 設(shè)置成功了,則設(shè)置失效時(shí)間
jedis.expire(key, expireSeconds);
} else if (!setnxOK && jedis.pttl(key) < 0) {// 或者由于某些異常狀態(tài)setnx執(zhí)行成功
// 但expire沒(méi)有成功,可能會(huì)導(dǎo)致鎖永遠(yuǎn)釋放不掉,這里強(qiáng)制設(shè)置過(guò)期時(shí)間
jedis.expire(key, expireSeconds);
}
}
if (setnxOK) {
return true;
}
} catch (Exception e) {
jedis.close();
e.printStackTrace();
} finally {
closeResource(jedis);
}
return false;
}
/**
* 設(shè)置一個(gè)全新的list<br/>
* 如果之前已經(jīng)存在key,則會(huì)先移除,再添加
*
* @param key
* @param list
*/
public static <T> void setList(String key, List<T> list) {
if (list == null || list.size() == 0) {
return;
}
Jedis jedis = pool.getResource();
try {
String[] ss = new String[list.size()];
for (int i = 0; i < list.size(); i++) {
ss[i] = JSONObject.toJSONString(list.get(i));
}
delKey(key);// 先移除之前的key,再新增
jedis.rpush(key, ss);
} catch (Exception e) {
jedis.close();
e.printStackTrace();
throw new RedisException(e.getMessage(), e);
} finally {
closeResource(jedis);
}
}
/**
*
* @param key
* @param list
* @param timeOut
* @param <T>
*/
public static <T> void setList(String key, List<T> list,Integer timeOut) {
if (list == null || list.size() == 0) {
return;
}
Jedis jedis = pool.getResource();
try {
String[] ss = new String[list.size()];
for (int i = 0; i < list.size(); i++) {
ss[i] = JSONObject.toJSONString(list.get(i));
}
jedis.rpush(key, ss);
jedis.expire(key,timeOut);
} catch (Exception e) {
jedis.close();
e.printStackTrace();
throw new RedisException(e.getMessage(), e);
} finally {
closeResource(jedis);
}
}
/**
* 添加一個(gè)value到原有列表到尾部
* @param key
* @param value
* @param <T>
*/
public static <T> void addList(String key, T value) {
Jedis jedis = pool.getResource();
try {
String[] ss = new String[1];
ss[0] = JSONObject.toJSONString(value);
jedis.rpush(key, ss);
} catch (Exception e) {
jedis.close();
e.printStackTrace();
throw new RedisException(e.getMessage(), e);
} finally {
closeResource(jedis);
}
}
/**
* 添加一個(gè)value到原有列表頭部
*
* @param key
* @param value
*/
public static <T> void addListToHead(String key, T value) {
Jedis jedis = pool.getResource();
try {
String[] ss = new String[1];
ss[0] = JSONObject.toJSONString(value);
jedis.lpush(key, JSONObject.toJSONString(value));
} catch (Exception e) {
jedis.close();
e.printStackTrace();
throw new RedisException(e.getMessage(), e);
} finally {
closeResource(jedis);
}
}
/**
* 設(shè)置list中指定索引的值
*
* @param key
* @param index-索引
* @param value
*/
public static <T> void setListElement(String key, int index, T value) {
Jedis jedis = pool.getResource();
try {
jedis.lset(key, index, JSONObject.toJSONString(value));
} catch (Exception e) {
jedis.close();
e.printStackTrace();
throw new RedisException(e.getMessage(), e);
} finally {
closeResource(jedis);
}
}
/**
* 返回某個(gè)范圍內(nèi)的集合,無(wú)結(jié)果集則返回空l(shuí)ist
*
* @param key
* @param start-起始索引(包含,從0開(kāi)始)
* @param end-結(jié)束索引(包含)
* @return
*/
private static List<String> getListRange(String key, int start, int end) {
Jedis jedis = pool.getResource();
try {
return jedis.lrange(key, start, end);
} catch (Exception e) {
jedis.close();
e.printStackTrace();
return null;
} finally {
closeResource(jedis);
}
}
/**
* 返回某個(gè)范圍內(nèi)的集合,無(wú)結(jié)果集則返回空l(shuí)ist
*
* @param key
* @param start-起始索引(包含,從0開(kāi)始)
* @param end-結(jié)束索引(包含)
* @param c-具體類(lèi)
* @return
*/
public static <T> List<T> getListRange(String key, int start, int end, Class<T> c) {
List<String> slist = getListRange(key, start, end);
List<T> list = new ArrayList<T>();
for (String s : slist) {
list.add(gson.fromJson(s, c));
}
return list.isEmpty() ? null : list;
}
/**
* 分頁(yè)獲取list
*
* @param key
* @param pageNow-當(dāng)前頁(yè)數(shù)
* @param pageSize-每頁(yè)記錄數(shù)
* @param c
* @return
*/
public static <T> List<T> getListPage(String key, int pageNow, int pageSize, Class<T> c) {
int startIndex = (pageNow - 1) * pageSize;
int endIndex = pageNow * pageSize - 1;
return getListRange(key, startIndex, endIndex, c);
}
/**
* 獲取指定key下的列表所有記錄
*
* @param key
* @param c
* @return
*/
public static <T> List<T> getAllList(String key, Class<T> c) {
return getListRange(key, 0, -1, c);
}
/**
* 獲取列表第一個(gè)元素
*
* @param key
* @param c
* @return
*/
public static <T> T getListFirstElement(String key, Class<T> c) {
Jedis jedis = pool.getResource();
try {
return JSONObject.parseObject(jedis.lindex(key, 0), c);
} catch (Exception e) {
jedis.close();
e.printStackTrace();
return null;
} finally {
closeResource(jedis);
}
}
/**
* 返回并刪除list中的首元素
*
* @param key
* @return
*/
public static <T> T getListPop(String key, Class<T> c) {
Jedis jedis = pool.getResource();
try {
return JSONObject.parseObject(jedis.lpop(key), c);
} catch (Exception e) {
jedis.close();
e.printStackTrace();
return null;
} finally {
closeResource(jedis);
}
}
/**
* 獲取列表最后一個(gè)元素
*
* @param key
* @param c
* @return
*/
public static <T> T getListLastElement(String key, Class<T> c) {
Jedis jedis = pool.getResource();
try {
return JSONObject.parseObject(jedis.lindex(key, -1), c);
} catch (Exception e) {
jedis.close();
e.printStackTrace();
return null;
} finally {
closeResource(jedis);
}
}
/**
* 返回list的集合個(gè)數(shù)
*
* @param key
* @return
*/
public static int getListSize(String key) {
Jedis jedis = pool.getResource();
try {
return jedis.llen(key).intValue();
} catch (Exception e) {
jedis.close();
e.printStackTrace();
return 0;
} finally {
closeResource(jedis);
}
}
/**
* 刪除list的指定對(duì)象
*
* @param key
* @param values
*/
@SuppressWarnings("unchecked")
public static <T> void removeValueFromList(String key, T... values) {
Jedis jedis = pool.getResource();
try {
for (T v : values) {
jedis.lrem(key, 0, JSONObject.toJSONString(v));
}
} catch (Exception e) {
jedis.close();
e.printStackTrace();
throw new RedisException(e.getMessage(), e);
} finally {
closeResource(jedis);
}
}
/**
* 刪除一個(gè)列表
*
* @param key
*/
public static void removeList(String key) {
Jedis jedis = pool.getResource();
try {
if (jedis.llen(key) > 0) {
jedis.ltrim(key, 1, 0);
}
} catch (Exception e) {
jedis.close();
e.printStackTrace();
throw new RedisException(e.getMessage(), e);
} finally {
closeResource(jedis);
}
}
/**
* 保存Java map to Redis map
* @param hashKey
* @param map
*/
public static <T> void addToHashMap(String hashKey, Map<String, T> map) {
if (map == null || map.isEmpty()) {
return;
}
Jedis jedis = pool.getResource();
try {
for (String key : map.keySet()) {
String value = JSONObject.toJSONString(map.get(key));
jedis.hset(hashKey, key, value);
}
jedis.expire(hashKey, DEFAULT_EXPIRE_SECONDS);
} catch (Exception e) {
jedis.close();
e.printStackTrace();
throw new RedisException(e.getMessage(), e);
} finally {
closeResource(jedis);
}
}
/**
* 保存Java map to Redis map
*
* @param hashKey
* @param map
*/
public static <K, V> void addToHashMap2(String hashKey, Map<K, V> map) {
if (map == null || map.isEmpty()) {
return;
}
Jedis jedis = pool.getResource();
try {
for (K key : map.keySet()) {
String value = JSONObject.toJSONString(map.get(key));
jedis.hset(hashKey, String.valueOf(key), value);
}
} catch (Exception e) {
jedis.close();
e.printStackTrace();
throw new RedisException(e.getMessage(), e);
} finally {
closeResource(jedis);
}
}
/**
* 保存Java value to Redis map
*
* @param hashKey
* @param key
* @param value
*/
public static <T> void addToHashMap(String hashKey, String key, T value) {
Jedis jedis = pool.getResource();
try {
jedis.hset(hashKey, key, JSONObject.toJSONString(value));
} catch (Exception e) {
jedis.close();
e.printStackTrace();
throw new RedisException(e.getMessage(), e);
} finally {
closeResource(jedis);
}
}
/**
* 從hashmap中返回某個(gè)key的值
*
* @param hashKey
* @param key
* @param c-類(lèi)型
* @return
*/
public static <T> T getValueFromHashMap(String hashKey, String key, Class<T> c) {
Jedis jedis = pool.getResource();
try {
String s = jedis.hget(hashKey, key);
if (StringUtils.isEmpty(s)) {
return null;
}
return JSONObject.parseObject(s, c);
} catch (Exception e) {
jedis.close();
e.printStackTrace();
return null;
} finally {
closeResource(jedis);
}
}
/**
* 從hashmap中返回某個(gè)key的值
* @param hashKey
* @param key
* @param typeOfT
* @param <T>
* @return
*/
public static <T> T getValueFromHashMap(String hashKey, String key, Type typeOfT) {
Jedis jedis = pool.getResource();
try {
String s = jedis.hget(hashKey, key);
if (StringUtils.isEmpty(s)) {
return null;
}
return JSONObject.parseObject(s, typeOfT);
} catch (Exception e) {
jedis.close();
e.printStackTrace();
return null;
} finally {
closeResource(jedis);
}
}
/**
* 返回整個(gè)map對(duì)象
*
* @param hashKey
* @return
*/
public static <T> Map<String, T> getAllFromHashMap(String hashKey, Class<T> c) {
Jedis jedis = pool.getResource();
try {
Map<String, String> map = jedis.hgetAll(hashKey);
Map<String, T> tMap = new HashMap<String, T>(map.size());
for (String key : map.keySet()) {
T value = JSONObject.parseObject(map.get(key), c);
tMap.put(key, value);
}
return tMap;
} catch (Exception e) {
jedis.close();
e.printStackTrace();
return null;
} finally {
closeResource(jedis);
}
}
/**
* 獲取hashmap的size
*
* @param hashKey
* @return
*/
public static long getSizeFromHashMap(String hashKey) {
Jedis jedis = pool.getResource();
try {
return jedis.hlen(hashKey);
} catch (Exception e) {
jedis.close();
e.printStackTrace();
return 0;
} finally {
closeResource(jedis);
}
}
/**
* 刪除map中的指定key
*
* @param hashKey
* @param keys
*/
public static void removeFromHashMap(String hashKey, String... keys) {
Jedis jedis = pool.getResource();
try {
jedis.hdel(hashKey, keys);
} catch (Exception e) {
jedis.close();
e.printStackTrace();
} finally {
closeResource(jedis);
}
}
/**
* 獲取某個(gè)Map的所有key集合
*
* @param hashKey
* @return
*/
public static Set<String> getKeysFromHashMap(String hashKey) {
Jedis jedis = pool.getResource();
try {
return jedis.hkeys(hashKey);
} catch (Exception e) {
jedis.close();
e.printStackTrace();
return null;
} finally {
closeResource(jedis);
}
}
/**
* 刪除某Map所有的元素
*
* @param hashKey
*/
public static void removeHashMap(String hashKey) {
if (StringUtils.isEmpty(hashKey)) {
return;
}
Set<String> keySet = getKeysFromHashMap(hashKey);
if (keySet == null || keySet.isEmpty()) {
return;
}
// 化成數(shù)組
String[] keyArr = keySet.toArray(new String[] {});
if (keyArr == null || keyArr.length == 0) {
return;
}
// 批量刪除
removeFromHashMap(hashKey, keyArr);
}
/**
* 在hashmap中是否存在指定的key
* @param hashKey
* @param key
* @return
*/
public static boolean hasKeyFromHashMap(String hashKey, String key) {
Jedis jedis = pool.getResource();
try {
return jedis.hexists(hashKey, key);
} catch (Exception e) {
jedis.close();
e.printStackTrace();
return false;
} finally {
closeResource(jedis);
}
}
Redis 有序集合和集合一樣也是string類(lèi)型元素的集合,且不允許重復(fù)的成員。
不同的是每個(gè)元素都會(huì)關(guān)聯(lián)一個(gè)double類(lèi)型的分?jǐn)?shù)。redis正是通過(guò)分?jǐn)?shù)來(lái)為集合中的成員進(jìn)行從小到大的排序。
有序集合的成員是唯一的,但分?jǐn)?shù)(score)卻可以重復(fù)。
集合是通過(guò)哈希表實(shí)現(xiàn)的,所以添加,刪除,查找的復(fù)雜度都是O(1)。 集合中最大的成員數(shù)為 232 - 1 (4294967295, 每個(gè)集合可存儲(chǔ)40多億個(gè)成員)。
/**
* 寫(xiě)入zset隊(duì)列
* @param key
* @param map
* @return
*/
public static boolean setZsetValue(String key, Map<String, Double> map) {
if (StringUtils.isEmpty(key)) {
return false;
}
if(map == null || map.size() <= 0) {
return false;
}
Jedis jedis = pool.getResource();
try {
Long count = jedis.zadd(key, map);
if(count > 0) {
return true;
}
} catch (Exception e) {
closeResource(jedis);
Logger.error("RedisClient->setZsetValue插入隊(duì)列失敗 map=[" + JSONObject.toJSONString(map) + "]", e);
} finally {
closeResource(jedis);
}
return false;
}
/**
* 根據(jù)范圍返回zSet隊(duì)列任務(wù)
* @param key
* @param minIndex
* @param maxIndex
* @return
*/
public static Set<String> getZsetValuesByRange(String key, int minIndex, int maxIndex) {
Set<String> set = Collections.emptySet();
if(existsKey(key)) {
if(getZsetCount(key) <= 0) {
return set;
}
Jedis jedis = pool.getResource();
try {
set = jedis.zrange(key, minIndex, maxIndex);
return set;
} catch (Exception e) {
closeResource(jedis);
Logger.error("RedisClient->getZsetValuesByRange獲取隊(duì)列任務(wù)失敗 key=[" + key + "], index=["+minIndex+","+maxIndex+"]", e);
} finally {
closeResource(jedis);
}
}
return set;
}
/**
* 根據(jù)Value刪除指定Zset隊(duì)列元素
* @param key
* @param value
* @return
*/
public static boolean remZsetValue(String key, String value) {
if (StringUtils.isEmpty(key)) {
return false;
}
if(existsKey(key)) {
Jedis jedis = pool.getResource();
try {
Long count = jedis.zrem(key, value);
if(count > 0) {
return true;
}
} catch (Exception e) {
closeResource(jedis);
Logger.error("RedisClient->remZsetValue刪除隊(duì)列任務(wù)失敗 key=[" + key + "], value=["+value+"]", e);
return false;
} finally {
closeResource(jedis);
}
}
return false;
}
public static long getZsetCount(String key) {
if (StringUtils.isEmpty(key)) {
return 0;
}
if(existsKey(key)) {
Jedis jedis = pool.getResource();
try {
return jedis.zcard(key);
} catch (Exception e) {
closeResource(jedis);
e.printStackTrace();
return 0;
} finally {
closeResource(jedis);
}
}
return 0;
}
Redis Hincrby 命令用于為哈希表中的字段值加上指定增量值。
增量也可以為負(fù)數(shù),相當(dāng)于對(duì)指定字段進(jìn)行減法操作。
如果哈希表的 key 不存在,一個(gè)新的哈希表被創(chuàng)建并執(zhí)行 HINCRBY 命令。
如果指定的字段不存在,那么在執(zhí)行命令前,字段的值被初始化為 0 。
對(duì)一個(gè)儲(chǔ)存字符串值的字段執(zhí)行 HINCRBY 命令將造成一個(gè)錯(cuò)誤。
本操作的值被限制在 64 位(bit)有符號(hào)數(shù)字表示之內(nèi)。
/**
* 為哈希表 key 中的域 field 的值加1
* @param key
* @param field
* @return
*/
public static long incrementHashMapValue(String key, String field) {
return incrementHashMapValue(key, field, 1);
}
/**
* 為哈希表 key 中的域 field 的值減1
* @param key
* @param field
* @return
*/
public static long decrementHashMapValue(String key, String field) {
return incrementHashMapValue(key, field, -1);
}
public static long incrementHashMapValue(String key, String field, long increment) {
Jedis jedis = pool.getResource();
try {
return jedis.hincrBy(key, field, increment);
} catch (Exception e) {
// Logger.error(e.getMessage(), e);
e.printStackTrace();
return -1;
} finally {
closeResource(jedis);
}
}
/**
* 添加set集合
*/
public static void addSetValue(String key, String value, int expireSeconds) {
Jedis jedis = pool.getResource();
try {
if (expireSeconds > 0) {
jedis.sadd(key, value);
jedis.expire(key, expireSeconds);
} else {// 不設(shè)置過(guò)期時(shí)間則需檢測(cè)之前是否設(shè)置有過(guò)期時(shí)間,有則需設(shè)置回原有的過(guò)期時(shí)間
// 獲取key過(guò)期時(shí)間,因?yàn)閟et后原有的key過(guò)期時(shí)間將被清空
long expireTime = jedis.pttl(key);// 剩余過(guò)期毫秒數(shù)
jedis.sadd(key, value);
if (expireTime > 0) {
int time = (int) Math.ceil((float) expireTime / 1000);
jedis.expire(key, time);// 再設(shè)置原有剩余秒數(shù) 向上取整,如2.1 則為3
}
}
} catch (Exception e) {
jedis.close();
e.printStackTrace();
throw new RedisException(e.getMessage(), e);
} finally {
closeResource(jedis);
}
}
/**
* 批量-添加set集合
*/
public static void addSetValue(String key, String[] value, int expireSeconds) {
Jedis jedis = pool.getResource();
try {
if (expireSeconds > 0) {
jedis.sadd(key, value);
jedis.expire(key, expireSeconds);
} else {// 不設(shè)置過(guò)期時(shí)間則需檢測(cè)之前是否設(shè)置有過(guò)期時(shí)間,有則需設(shè)置回原有的過(guò)期時(shí)間
// 獲取key過(guò)期時(shí)間,因?yàn)閟et后原有的key過(guò)期時(shí)間將被清空
long expireTime = jedis.pttl(key);// 剩余過(guò)期毫秒數(shù)
jedis.sadd(key, value);
if (expireTime > 0) {
int time = (int) Math.ceil((float) expireTime / 1000);
jedis.expire(key, time);// 再設(shè)置原有剩余秒數(shù) 向上取整,如2.1 則為3
}
}
} catch (Exception e) {
jedis.close();
e.printStackTrace();
throw new RedisException(e.getMessage(), e);
} finally {
closeResource(jedis);
}
}
/**
* 移除集合中一個(gè)或多個(gè)成員
* @param key
* @param members
* @return
*/
public static boolean delSetValues(String key, String... members){
Jedis jedis = null;
try {
jedis = pool.getResource();
Long value = jedis.srem(key, members);
if(value > 0){
return true;
}
}catch (Exception e) {
e.printStackTrace();
}finally{
if(jedis != null){
jedis.close();
}
}
return false;
}
/**
* 獲取set集合
*/
public static Set<String> getSetValue(String key) {
Jedis jedis = pool.getResource();
try {
return jedis.smembers(key);
} catch (Exception e) {
jedis.close();
e.printStackTrace();
return Sets.newHashSet();
} finally {
closeResource(jedis);
}
}
/**
* 獲取對(duì)象轉(zhuǎn)換的Set集合
* @param key
* @param c
* @param <T>
* @return
*/
public static <T> Set<T> getSetValue(String key, Class<T> c) {
Set<String> set = getSetValue(key);
Set<T> temp = new HashSet<>();
if(set.size() > 0){
for (String s : set) {
temp.add(JSONObject.parseObject(s, c));
}
}
return temp;
}
/**
* 彈出Set集合
* @param sourceKey
* @param targetKey
* @return
*/
public static Set<String> moveSetValue(String sourceKey, String targetKey){
Jedis jedis = pool.getResource();
try {
//獲取當(dāng)前列表元素
Set<String> currentSet = jedis.smembers(sourceKey);
if(currentSet.size() <= 0){
return Sets.newHashSet();
}
//將元素移到另外一個(gè)集合
for (String value :currentSet){
jedis.smove(sourceKey, targetKey, value);
}
Set<String> set = jedis.smembers(targetKey);
return set;
} catch (Exception e) {
jedis.close();
e.printStackTrace();
return Sets.newHashSet();
} finally {
closeResource(jedis);
}
}
/**
* 彈出Set對(duì)象集合
* @param sourceKey
* @param targetKey
* @param c
* @param <T>
* @return
*/
public static <T> Set<T> moveSetValue(String sourceKey, String targetKey, Class<T> c) {
Set<String> set = moveSetValue(sourceKey, targetKey);
Set<T> temp = new HashSet<>();
if(set.size() > 0){
for (String s : set) {
temp.add(JSONObject.parseObject(s, c));
}
}
return temp;
}
/**
* 獲取Set集合總數(shù)
* @param key
* @return
*/
public static long getSetCount(String key) {
Jedis jedis = pool.getResource();
try {
return jedis.scard(key);
} catch (Exception e) {
jedis.close();
e.printStackTrace();
return BasicDataUtil.DEFAULT_LONG;
} finally {
closeResource(jedis);
}
}
/**
* 查詢(xún)set集合內(nèi)是否存在該元素
* @param key
* @param val
* @return
*/
public static Boolean existsKeyInSet(String key, String val) {
Jedis jedis = pool.getResource();
try {
return jedis.sismember(key, val);
} catch (Exception e) {
jedis.close();
e.printStackTrace();
return Boolean.FALSE;
} finally {
closeResource(jedis);
}
}
/**
* 從set集合中彈出一定數(shù)量的元素(數(shù)量由傳入?yún)?shù)控制)
*/
public static Set<String> getSetValueBySpop(String key, long count){
Jedis jedis = pool.getResource();
Set<String> value;
try {
value = jedis.spop(key,count);
}catch (Exception e) {
jedis.close();
e.printStackTrace();
return new HashSet<>();
} finally {
closeResource(jedis);
}
return value;
}
Redis提供的API函數(shù)十分豐富,能幫助我們解決系統(tǒng)中很多性能問(wèn)題。后續(xù)會(huì)提供一些用到Redis的技術(shù)方案。