實現 登陸時
//存儲key到redis shi效未1920秒
RedisUtils.setObject(id,key,1920);
接口判斷讀取時
/**
* 驗證token
* @param id
* @param version_code
* @return int
* @throws ParseException
*/
public int CodeRedis(String id,String version_code) throws ParseException {
String tokens=RedisUtils.getObject(id).toString();
//token驗證成功
if(tokens.equals(version_code) && !tokens.equals("0")){
return 1;
//token驗證失敗
}else if(!tokens.equals(version_code) && !tokens.equals("0")){
return 0;
//id redis中沒有 去數據庫判斷 數據庫超過35分會自動更新token
}else {
UUID uuid = UUID.randomUUID();
String key= uuid.toString();
Map<String, Object> returnMap=new HashMap<String, Object>();
List<Map<String, Object>> list = xxxxxx(version_code,id,key);
//驗證成功在redis中存token
if(Integer.parseInt(list.get(0).get("codes").toString())>0){
long a = new Date().getTime();
SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
Date date = sdf.parse( list.get(0).get("code_date").toString() );
long b = date.getTime();
int c = (int)((a - b) / 1000);
RedisUtils.setObject(id,list.get(0).get("version_code"),1920-c);
}
//失敗返回0
return Integer.parseInt(list.get(0).get("codes").toString());
}
}
每30分更新redis的token和數據庫token重置更新時間保證redis都有token存在,(前端請求)
工具類 PropertiesUtils
package com.springboot.exam.controller.redis;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.log4j.Logger;
/**
* @author jwang
* properties文件讀寫工具類
*
*/
public abstract class PropertiesUtils
{
private static final Logger LOG = Logger.getLogger(PropertiesUtils.class);
public static Properties getProperties(String path)
{
Properties prop = new Properties();
loadProp(prop, path);
return prop;
}
private static void loadProp(Properties p, String conf)
{
InputStream is = getInputStream(conf);
if(null != is)
{
try
{
p.load(is);
}
catch (IOException e)
{
LOG.info("file not found!");
}
finally
{
if(is != null)
{
try
{
is.close();
}
catch (IOException e)
{
LOG.info("stream close fail!");
}
}
}
}
}
//獲取輸入流
private static InputStream getInputStream(String conf)
{
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream is = null;
if(null != classLoader)
{
is = classLoader.getResourceAsStream(conf);
}
return is;
}
//獲取輸出流
private static OutputStream getOutPutStream(String conf)
{
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
OutputStream out = null;
if(null != classLoader)
{
String filePath = classLoader.getResource(conf).getFile();
try
{
out = new FileOutputStream(filePath);
}
catch (FileNotFoundException e)
{
LOG.info("file not found!!!");
}
}
return out;
}
//讀取key=value
public static String getValue(Properties p, String key)
{
String value = p.getProperty(key);
return value == null?"":value;
}
//設置key=value
public static void setValue(String conf, String key, String value)
{
Properties p = getProperties(conf);
OutputStream out = getOutPutStream(conf);
p.setProperty(key, value);
try
{
p.store(out, "set:"+key+"="+value);
}
catch (IOException e)
{
LOG.info("set properties fail!!!");
}
finally
{
if(out != null)
{
try
{
out.close();
}
catch (IOException e)
{
LOG.info("stream close fail!");
}
}
}
}
}
RedisUtils:
package com.springboot.exam.controller.redis;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import redis.clients.jedis.BinaryClient.LIST_POSITION;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.util.SafeEncoder;
/**
* redis操作工具類
* @author jwang
*
*/
public class RedisUtils
{
private static Logger logger = LoggerFactory.getLogger(RedisUtils.class);
//獲取連接參數
// Redis服務器地址
private static final String REDIS_ADDR = "127.0.0.1";
//Redis服務器連接端口
private static final String REDIS_PORT = "6379";
// 連接池最大連接數(使用負值表示沒有限制)
private static final String REDIS_MAXACTIVE = "200";
//連接池中的最大空閒連接
private static final String REDIS_MAXIDLE = "10";
//連接池最大阻塞等待時間(使用負值表示沒有限制)
private static final String REDIS_MAXWAIt = "-1";
//連接超時時間(毫秒)
private static final String REDIS_TIMEOUT = "6000";
//Redis服務器連接密碼(默認爲空)
private static final String REDIS_PASSWORD = "123456";
//private static final String REDIS_TESTONBORROW = PROP.getProperty("redis.pool.testOnBorrow");
private static JedisPool jedisPool = null;
//初始化redis連接池
static
{
try
{
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(Integer.parseInt(REDIS_MAXACTIVE));
config.setMaxIdle(Integer.parseInt(REDIS_MAXIDLE));
config.setMaxWaitMillis(Integer.parseInt(REDIS_MAXWAIt));
config.setTestOnBorrow(Boolean.parseBoolean(String.valueOf(true)));
jedisPool = new JedisPool(config, REDIS_ADDR, Integer.parseInt(REDIS_PORT),
Integer.parseInt(REDIS_TIMEOUT), REDIS_PASSWORD);
}
catch (Exception e)
{
logger.error("Jedis pool create fail!!!");
e.printStackTrace();
}
}
/**
* 獲取Jedis實例
* @return
*/
public static synchronized Jedis getJedis()
{
try
{
if (jedisPool != null)
{
Jedis resource = jedisPool.getResource();
return resource;
}
else
{
return null;
}
}
catch (Exception e)
{
logger.error("Jedis get fail!!!");
e.printStackTrace();
return null;
}
}
/**
* 釋放jedis資源
* @param jedis
*/
public static void closeResource(final Jedis jedis)
{
if (jedis != null)
{
jedis.close();
}
}
/**
* 獲取redis鍵值-object
*
* @param key
* @return
*/
public static Object getObject(String key)
{
Jedis jedis = null;
try
{
jedis = jedisPool.getResource();
byte[] bytes = jedis.get(key.getBytes());
if(!StringUtils.isEmpty(bytes))
{
return SerializeUtils.unserialize(bytes);
}else {
return "0";
}
}
catch (Exception e)
{
logger.error("getObject獲取redis鍵值異常:key=" + key + " cause:" + e.getMessage());
}
finally
{
jedis.close();
}
return null;
}
/**
* 設置redis-object
* @param key
* @param value
* @return
*/
public static String setObject(String key, Object value)
{
Jedis jedis = null;
try
{
jedis = jedisPool.getResource();
return jedis.set(key.getBytes(), SerializeUtils.serialize(value));
}
catch (Exception e)
{
logger.error("setObject設置redis鍵值異常:key=" + key + " value=" + value + " cause:" + e.getMessage());
return null;
}
finally
{
if(jedis != null)
{
jedis.close();
}
}
}
/**
* 添加key-value及設置過期時間
* @param key
* @param value
* @param expiretime
* @return
*/
public static String setObject(String key, Object value, int expiretime)
{
String result = "";
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
result = jedis.set(key.getBytes(), SerializeUtils.serialize(value));
if(result.equals("OK"))
{
jedis.expire(key.getBytes(), expiretime);
}
return result;
}
catch (Exception e)
{
logger.error("setObject設置redis鍵值異常:key=" + key + " value=" + value + " cause:" + e.getMessage());
}
finally
{
if(jedis != null)
{
jedis.close();
}
}
return result;
}
/**
* 刪除key
* @param key
* @return
*/
public Long delkeyObject(String key)
{
Jedis jedis = null;
try
{
jedis = jedisPool.getResource();
return jedis.del(key.getBytes());
}
catch(Exception e)
{
e.printStackTrace();
return null;
}
finally{
if(jedis != null)
{
jedis.close();
}
}
}
/**
* 判斷某個key是否存在
* @param key
* @return
*/
public Boolean existsObject(String key)
{
Jedis jedis = null;
try
{
jedis = jedisPool.getResource();
return jedis.exists(key.getBytes());
}
catch(Exception e)
{
e.printStackTrace();
return null;
}
finally
{
if(jedis != null)
{
jedis.close();
}
}
}
/**
* 清空所有key
*/
public String flushAll()
{
Jedis jedis = getJedis();
String stata = jedis.flushAll();
closeResource(jedis);
return stata;
}
/**
* 更改key
* @param String oldkey
* @param String newkey
* @return 狀態碼
*
*/
public String rename(String oldkey,String newkey)
{
Jedis jedis = getJedis();
String status = jedis.rename(oldkey.getBytes(), newkey.getBytes());
closeResource(jedis);
return status;
}
/**
* 設置key的過期時間,以秒爲單位
* @param String key
* @param 時間,以秒爲單位
* @return 影響的記錄數
*
*/
public long expired(String key, int seconds)
{
Jedis jedis = getJedis();
long count = jedis.expire(key, seconds);
closeResource(jedis);
return count;
}
/**
* 取消對key過期時間的設置
* @param key
* @return 影響的記錄數
*/
public long persist(String key)
{
Jedis jedis = getJedis();
long count = jedis.persist(key);
closeResource(jedis);
return count;
}
/**
* 刪除keys對應的記錄,可以是多個key
* @param String ... keys
* @return 刪除的記錄數
* */
public long del(String... keys)
{
Jedis jedis = getJedis();
long count = jedis.del(keys);
closeResource(jedis);
return count;
}
/**
* 刪除keys對應的記錄,可以是多個key
* @param String .. keys
* @return 刪除的記錄數
*/
public long del(byte[]... keys)
{
Jedis jedis = getJedis();
long count = jedis.del(keys);
closeResource(jedis);
return count;
}
/**
* 返回指定key存儲的類型
* @param String key
* @return String string|list|set|zset|hash
*/
public String type(String key)
{
Jedis jedis=getJedis();
String type = jedis.type(key);
closeResource(jedis);
return type;
}
/**
* 查找所有匹配給定的模式的鍵
* @param String key的表達式,*表示多個,?表示一個
*/
public Set<String> keys(String pattern)
{
Jedis jedis = getJedis();
Set<String> set = jedis.keys(pattern);
closeResource(jedis);
return set;
}
//********************Sets*****************//
/**
* 向Set添加一條記錄,如果member已存在返回0,否則返回1
* @param String key
* @param String member
* @return 操作碼,0或1
*/
public long setAdd(String key, String member)
{
Jedis jedis = getJedis();
long status = jedis.sadd(key, member);
closeResource(jedis);
return status;
}
public long setAdd(byte[] key, byte[] member)
{
Jedis jedis = getJedis();
long status = jedis.sadd(key, member);
closeResource(jedis);
return status;
}
/**
* 獲取給定key的set中元素個數
* @param String key
* @return 元素個數
*/
public long scard(String key)
{
Jedis jedis = getJedis();
long len = jedis.scard(key);
closeResource(jedis);
return len;
}
/**
* 返回從第一組和所有的給定集合之間的差異的成員
* @param String ... keys
* @return 差異的成員集合
*/
public Set<String> sdiff(String... keys)
{
Jedis jedis = getJedis();
Set<String> set = jedis.sdiff(keys);
closeResource(jedis);
return set;
}
/**
* 這個命令等於sdiff,但返回的不是結果集,而是將結果集存儲在新的集合中,如果目標已存在,則覆蓋。
* @param String newkey 新結果集的key
* @param String ... keys 比較的集合
* @return 新集合中的記錄數
*/
public long sdiffstore(String newkey, String... keys)
{
Jedis jedis = getJedis();
long s = jedis.sdiffstore(newkey, keys);
closeResource(jedis);
return s;
}
/**
* 返回給定集合交集的成員,如果其中一個集合爲不存在或爲空,則返回空Set
* @param String ... keys
* @return 交集成員的集合
*/
public Set<String> sinter(String... keys)
{
Jedis jedis = getJedis();
Set<String> set = jedis.sinter(keys);
closeResource(jedis);
return set;
}
/**
* 這個命令等於sinter,但返回的不是結果集,而是將結果集存儲在新的集合中,如果目標已存在,則覆蓋。
* @param String newkey 新結果集的key
* @param String ... keys 比較的集合
* @return 新集合中的記錄數
*/
public long sinterstore(String newkey, String... keys)
{
Jedis jedis = getJedis();
long s = jedis.sinterstore(newkey, keys);
closeResource(jedis);
return s;
}
/**
* 確定一個給定的值是否存在
* @param String key
* @param String member 要判斷的值
* @return 存在返回1,不存在返回0
*/
public boolean sismember(String key, String member)
{
Jedis jedis = getJedis();
boolean status = jedis.sismember(key, member);
closeResource(jedis);
return status;
}
/**
* 返回集合中的所有成員
* @param String key
* @return 成員集合
* */
public Set<String> smembers(String key)
{
Jedis jedis = getJedis();
Set<String> set = jedis.smembers(key);
closeResource(jedis);
return set;
}
public Set<byte[]> smembers(byte[] key)
{
Jedis jedis = getJedis();
Set<byte[]> set = jedis.smembers(key);
closeResource(jedis);
return set;
}
/**
* 將成員從源集合移出放入目標集合
* 如果源集合不存在或不包哈指定成員,不進行任何操作,返回0
* 否則該成員從源集合上刪除,並添加到目標集合,如果目標集合中成員已存在,則只在源集合進行刪除
* @param String srckey 源集合
* @param String dstkey 目標集合
* @param String member 源集合中的成員
* @return 狀態碼,1成功,0失敗
*/
public long smove(String srckey, String dstkey, String member)
{
Jedis jedis = getJedis();
long s = jedis.smove(srckey, dstkey, member);
closeResource(jedis);
return s;
}
/**
* 從集合中刪除成員
* @param String key
* @return 被刪除的成員
*/
public String spop(String key)
{
Jedis jedis = getJedis();
String s = jedis.spop(key);
closeResource(jedis);
return s;
}
/**
* 從集合中刪除指定成員
* @param String key
* @param String member 要刪除的成員
* @return 狀態碼,成功返回1,成員不存在返回0
*/
public long srem(String key, String member)
{
Jedis jedis = getJedis();
long s = jedis.srem(key, member);
closeResource(jedis);
return s;
}
/**
* 合併多個集合並返回合併後的結果,合併後的結果集合並不保存
* @param String ... keys
* @return 合併後的結果集合
* @see sunionstore
* */
public Set<String> sunion(String... keys)
{
Jedis jedis = getJedis();
Set<String> set = jedis.sunion(keys);
closeResource(jedis);
return set;
}
/**
* 合併多個集合並將合併後的結果集保存在指定的新集合中,如果新集合已經存在則覆蓋
* @param String newkey 新集合的key
* @param String ... keys 要合併的集合
*/
public long sunionstore(String newkey, String... keys)
{
Jedis jedis = getJedis();
long s = jedis.sunionstore(newkey, keys);
closeResource(jedis);
return s;
}
//********************SortSet*****************//
/**
* 向集合中增加一條記錄,如果這個值已存在,這個值對應的權重將被置爲新的權重
* @param String key
* @param double score 權重
* @param String member 要加入的值,
* @return 狀態碼 1成功,0已存在member的值
*/
public long zadd(String key, double score, String member)
{
Jedis jedis = getJedis();
long status = jedis.zadd(key, score, member);
closeResource(jedis);
return status;
}
/**
* 獲取集合中元素的數量
* @param String key
* @return 如果返回0則集合不存在
*/
public long zcard(String key)
{
Jedis jedis = getJedis();
long len = jedis.zcard(key);
closeResource(jedis);
return len;
}
/**
* 獲取指定權重區間內集合的數量
* @param String key
* @param double min 最小排序位置
* @param double max 最大排序位置
* */
public long zcount(String key, double min, double max)
{
Jedis jedis = getJedis();
long len = jedis.zcount(key, min, max);
closeResource(jedis);
return len;
}
/**
* 獲得set的長度
*
* @param key
* @return
*/
public long zlength(String key)
{
long len = 0;
Set<String> set = zrange(key, 0, -1);
len = set.size();
return len;
}
/**
* 權重增加給定值,如果給定的member已存在
* @param String key
* @param double score 要增的權重
* @param String member 要插入的值
* @return 增後的權重
* */
public double zincrby(String key, double score, String member)
{
Jedis jedis = getJedis();
double s = jedis.zincrby(key, score, member);
closeResource(jedis);
return s;
}
/**
* 返回指定位置的集合元素,0爲第一個元素,-1爲最後一個元素
* @param String key
* @param int start 開始位置(包含)
* @param int end 結束位置(包含)
* @return Set<String>
* */
public Set<String> zrange(String key, int start, int end)
{
Jedis jedis = getJedis();
Set<String> set = jedis.zrange(key, start, end);
closeResource(jedis);
return set;
}
/**
* 返回指定權重區間的元素集合
* @param String key
* @param double min 上限權重
* @param double max 下限權重
* @return Set<String>
* */
public Set<String> zrangeByScore(String key, double min, double max)
{
Jedis jedis = getJedis();
Set<String> set = jedis.zrangeByScore(key, min, max);
closeResource(jedis);
return set;
}
/**
* 獲取指定值在集合中的位置,集合排序從低到高
* @see zrevrank
* @param String key
* @param String member
* @return long 位置
* */
public long zrank(String key, String member)
{
Jedis jedis = getJedis();
long index = jedis.zrank(key, member);
closeResource(jedis);
return index;
}
/**
* 獲取指定值在集合中的位置,集合排序從高到低
* @see zrank
* @param String key
* @param String member
* @return long 位置
* */
public long zrevrank(String key, String member)
{
Jedis jedis = getJedis();
long index = jedis.zrevrank(key, member);
closeResource(jedis);
return index;
}
/**
* 從集合中刪除成員
* @param String key
* @param String member
* @return 返回1成功
* */
public long zrem(String key, String member)
{
Jedis jedis = getJedis();
long s = jedis.zrem(key, member);
closeResource(jedis);
return s;
}
/**
* 刪除
* @param key
* @return
*/
public long zrem(String key)
{
Jedis jedis = getJedis();
long s = jedis.del(key);
closeResource(jedis);
return s;
}
/**
* 刪除給定位置區間的元素
* @param String key
* @param int start 開始區間,從0開始(包含)
* @param int end 結束區間,-1爲最後一個元素(包含)
* @return 刪除的數量
* */
public long zremrangeByRank(String key, int start, int end)
{
Jedis jedis = getJedis();
long s = jedis.zremrangeByRank(key, start, end);
closeResource(jedis);
return s;
}
/**
* 刪除給定權重區間的元素
* @param String key
* @param double min 下限權重(包含)
* @param double max 上限權重(包含)
* @return 刪除的數量
* */
public long zremrangeByScore(String key, double min, double max)
{
Jedis jedis = getJedis();
long s = jedis.zremrangeByScore(key, min, max);
closeResource(jedis);
return s;
}
/**
* 獲取給定區間的元素,原始按照權重由高到低排序
* @param String key
* @param int start
* @param int end
* @return Set<String>
* */
public Set<String> zrevrange(String key, int start, int end)
{
Jedis jedis = getJedis();
Set<String> set = jedis.zrevrange(key, start, end);
closeResource(jedis);
return set;
}
/**
* 獲取給定值在集合中的權重
* @param String key
* @param memeber
* @return double 權重
* */
public double zscore(String key, String memebr)
{
Jedis jedis = getJedis();
Double score = jedis.zscore(key, memebr);
closeResource(jedis);
if (score != null)
return score;
return 0;
}
//**********************Hash*************************//
/**
* 從hash中刪除指定的存儲
* @param String key
* @param String fieid 存儲的名字
* @return 狀態碼,1成功,0失敗
* */
public long hdel(String key, String fieid)
{
Jedis jedis = getJedis();
long s = jedis.hdel(key, fieid);
closeResource(jedis);
return s;
}
public long hdel(String key)
{
Jedis jedis = getJedis();
long s = jedis.del(key);
closeResource(jedis);
return s;
}
/**
* 測試hash中指定的存儲是否存在
* @param String key
* @param String fieid 存儲的名字
* @return 1存在,0不存在
* */
public boolean hexists(String key, String fieid)
{
Jedis jedis = getJedis();
boolean s = jedis.hexists(key, fieid);
closeResource(jedis);
return s;
}
/**
* 返回hash中指定存儲位置的值
*
* @param String key
* @param String fieid 存儲的名字
* @return 存儲對應的值
* */
public String hget(String key, String fieid)
{
Jedis jedis = getJedis();
String s = jedis.hget(key, fieid);
closeResource(jedis);
return s;
}
public byte[] hget(byte[] key, byte[] fieid)
{
Jedis jedis = getJedis();
byte[] s = jedis.hget(key, fieid);
closeResource(jedis);
return s;
}
/**
* 以Map的形式返回hash中的存儲和值
* @param String key
* @return Map<Strinig,String>
* */
public Map<String, String> hgetAll(String key)
{
Jedis jedis = getJedis();
Map<String, String> map = jedis.hgetAll(key);
closeResource(jedis);
return map;
}
/**
* 添加一個對應關係
* @param String key
* @param String fieid
* @param String value
* @return 狀態碼 1成功,0失敗,fieid已存在將更新,也返回0
* **/
public long hset(String key, String fieid, String value)
{
Jedis jedis = getJedis();
long s = jedis.hset(key, fieid, value);
closeResource(jedis);
return s;
}
public long hset(String key, String fieid, byte[] value)
{
Jedis jedis = getJedis();
long s = jedis.hset(key.getBytes(), fieid.getBytes(), value);
closeResource(jedis);
return s;
}
/**
* 添加對應關係,只有在fieid不存在時才執行
* @param String key
* @param String fieid
* @param String value
* @return 狀態碼 1成功,0失敗fieid已存
* **/
public long hsetnx(String key, String fieid, String value)
{
Jedis jedis = getJedis();
long s = jedis.hsetnx(key, fieid, value);
closeResource(jedis);
return s;
}
/**
* 獲取hash中value的集合
*
* @param String
* key
* @return List<String>
* */
public List<String> hvals(String key)
{
Jedis jedis = getJedis();
List<String> list = jedis.hvals(key);
closeResource(jedis);
return list;
}
/**
* 在指定的存儲位置加上指定的數字,存儲位置的值必須可轉爲數字類型
* @param String key
* @param String fieid 存儲位置
* @param String long value 要增加的值,可以是負數
* @return 增加指定數字後,存儲位置的值
* */
public long hincrby(String key, String fieid, long value)
{
Jedis jedis = getJedis();
long s = jedis.hincrBy(key, fieid, value);
closeResource(jedis);
return s;
}
/**
* 返回指定hash中的所有存儲名字,類似Map中的keySet方法
* @param String key
* @return Set<String> 存儲名稱的集合
* */
public Set<String> hkeys(String key)
{
Jedis jedis = getJedis();
Set<String> set = jedis.hkeys(key);
closeResource(jedis);
return set;
}
/**
* 獲取hash中存儲的個數,類似Map中size方法
* @param String key
* @return long 存儲的個數
* */
public long hlen(String key)
{
Jedis jedis = getJedis();
long len = jedis.hlen(key);
closeResource(jedis);
return len;
}
/**
* 根據多個key,獲取對應的value,返回List,如果指定的key不存在,List對應位置爲null
* @param String key
* @param String ... fieids 存儲位置
* @return List<String>
* */
public List<String> hmget(String key, String... fieids)
{
//ShardedJedis jedis = getShardedJedis();
Jedis jedis = getJedis();
List<String> list = jedis.hmget(key, fieids);
closeResource(jedis);
return list;
}
public List<byte[]> hmget(byte[] key, byte[]... fieids)
{
//ShardedJedis jedis = getShardedJedis();
Jedis jedis = getJedis();
List<byte[]> list = jedis.hmget(key, fieids);
closeResource(jedis);
return list;
}
/**
* 添加對應關係,如果對應關係已存在,則覆蓋
* @param Strin key
* @param Map <String,String> 對應關係
* @return 狀態,成功返回OK
* */
public String hmset(String key, Map<String, String> map)
{
Jedis jedis = getJedis();
String s = jedis.hmset(key, map);
closeResource(jedis);
return s;
}
/**
* 添加對應關係,如果對應關係已存在,則覆蓋
* @param Strin key
* @param Map <String,String> 對應關係
* @return 狀態,成功返回OK
* */
public String hmset(byte[] key, Map<byte[], byte[]> map) {
Jedis jedis = getJedis();
String s = jedis.hmset(key, map);
closeResource(jedis);
return s;
}
//**********************Strings*********************//
/**
* 根據key獲取記錄
* @param String key
* @return 值
* */
public String get(String key)
{
Jedis jedis = getJedis();
String value = jedis.get(key);
closeResource(jedis);
return value;
}
/**
* 根據key獲取記錄
* @param byte[] key
* @return 值
* */
public byte[] get(byte[] key)
{
Jedis jedis = getJedis();
byte[] value = jedis.get(key);
closeResource(jedis);
return value;
}
/**
* 添加有過期時間的記錄
*
* @param String key
* @param int seconds 過期時間,以秒爲單位
* @param String value
* @return String 操作狀態
* */
public String setEx(String key, int seconds, String value)
{
Jedis jedis = getJedis();
String str = jedis.setex(key, seconds, value);
closeResource(jedis);
return str;
}
/**
* 添加有過期時間的記錄
*
* @param String key
* @param int seconds 過期時間,以秒爲單位
* @param String value
* @return String 操作狀態
* */
public String setEx(byte[] key, int seconds, byte[] value)
{
Jedis jedis = getJedis();
String str = jedis.setex(key, seconds, value);
closeResource(jedis);
return str;
}
/**
* 添加一條記錄,僅當給定的key不存在時才插入
* @param String key
* @param String value
* @return long 狀態碼,1插入成功且key不存在,0未插入,key存在
* */
public long setnx(String key, String value)
{
Jedis jedis = getJedis();
long str = jedis.setnx(key, value);
closeResource(jedis);
return str;
}
/**
* 添加記錄,如果記錄已存在將覆蓋原有的value
* @param String key
* @param String value
* @return 狀態碼
* */
public String set(String key, String value)
{
return set(SafeEncoder.encode(key), SafeEncoder.encode(value));
}
/**
* 添加記錄,如果記錄已存在將覆蓋原有的value
* @param String key
* @param String value
* @return 狀態碼
* */
public String set(String key, byte[] value)
{
return set(SafeEncoder.encode(key), value);
}
/**
* 添加記錄,如果記錄已存在將覆蓋原有的value
* @param byte[] key
* @param byte[] value
* @return 狀態碼
* */
public String set(byte[] key, byte[] value)
{
Jedis jedis = getJedis();
String status = jedis.set(key, value);
closeResource(jedis);
return status;
}
/**
* 從指定位置開始插入數據,插入的數據會覆蓋指定位置以後的數據
* 例:String str1="123456789";<br/>
* 對str1操作後setRange(key,4,0000),str1="123400009";
* @param String key
* @param long offset
* @param String value
* @return long value的長度
* */
public long setRange(String key, long offset, String value)
{
Jedis jedis = getJedis();
long len = jedis.setrange(key, offset, value);
closeResource(jedis);
return len;
}
/**
* 在指定的key中追加value
* @param String key
* @param String value
* @return long 追加後value的長度
* **/
public long append(String key, String value)
{
Jedis jedis = getJedis();
long len = jedis.append(key, value);
closeResource(jedis);
return len;
}
/**
* 將key對應的value減去指定的值,只有value可以轉爲數字時該方法纔可用
* @param String key
* @param long number 要減去的值
* @return long 減指定值後的值
* */
public long decrBy(String key, long number)
{
Jedis jedis = getJedis();
long len = jedis.decrBy(key, number);
closeResource(jedis);
return len;
}
/**
* 可以作爲獲取唯一id的方法
* 將key對應的value加上指定的值,只有value可以轉爲數字時該方法纔可用
* @param String key
* @param long number 要減去的值
* @return long 相加後的值
* */
public long incrBy(String key, long number)
{
Jedis jedis = getJedis();
long len = jedis.incrBy(key, number);
closeResource(jedis);
return len;
}
/**
* 對指定key對應的value進行截取
* @param String key
* @param long startOffset 開始位置(包含)
* @param long endOffset 結束位置(包含)
* @return String 截取的值
* */
public String getrange(String key, long startOffset, long endOffset)
{
Jedis jedis = getJedis();
String value = jedis.getrange(key, startOffset, endOffset);
closeResource(jedis);
return value;
}
/**
* 獲取並設置指定key對應的value
* 如果key存在返回之前的value,否則返回null
* @param String key
* @param String value
* @return String 原始value或null
* */
public String getSet(String key, String value)
{
Jedis jedis = getJedis();
String str = jedis.getSet(key, value);
closeResource(jedis);
return str;
}
/**
* 批量獲取記錄,如果指定的key不存在返回List的對應位置將是null
* @param String keys
* @return List<String> 值得集合
* */
public List<String> mget(String... keys)
{
Jedis jedis = getJedis();
List<String> str = jedis.mget(keys);
closeResource(jedis);
return str;
}
/**
* 批量存儲記錄
* @param String keysvalues 例:keysvalues="key1","value1","key2","value2";
* @return String 狀態碼
* */
public String mset(String... keysvalues)
{
Jedis jedis = getJedis();
String str = jedis.mset(keysvalues);
closeResource(jedis);
return str;
}
/**
* 獲取key對應的值的長度
* @param String key
* @return value值得長度
* */
public long strlen(String key)
{
Jedis jedis = getJedis();
long len = jedis.strlen(key);
closeResource(jedis);
return len;
}
//***********************Lists******************//
/**
* List長度
* @param String key
* @return 長度
* */
public long llen(String key)
{
return llen(SafeEncoder.encode(key));
}
/**
* List長度
* @param byte[] key
* @return 長度
* */
public long llen(byte[] key)
{
Jedis jedis = getJedis();
long count = jedis.llen(key);
closeResource(jedis);
return count;
}
/**
* 覆蓋操作,將覆蓋List中指定位置的值
* @param byte[] key
* @param int index 位置
* @param byte[] value 值
* @return 狀態碼
* */
public String lset(byte[] key, int index, byte[] value)
{
Jedis jedis = getJedis();
String status = jedis.lset(key, index, value);
closeResource(jedis);
return status;
}
/**
* 覆蓋操作,將覆蓋List中指定位置的值
* @param key
* @param int index 位置
* @param String value 值
* @return 狀態碼
* */
public String lset(String key, int index, String value)
{
return lset(SafeEncoder.encode(key), index,
SafeEncoder.encode(value));
}
/**
* 在value的相對位置插入記錄
* @param key
* @param LIST_POSITION 前面插入或後面插入
* @param String pivot 相對位置的內容
* @param String value 插入的內容
* @return 記錄總數
* */
public long linsert(String key, LIST_POSITION where, String pivot,
String value)
{
return linsert(SafeEncoder.encode(key), where,
SafeEncoder.encode(pivot), SafeEncoder.encode(value));
}
/**
* 在指定位置插入記錄
* @param String key
* @param LIST_POSITION 前面插入或後面插入
* @param byte[] pivot 相對位置的內容
* @param byte[] value 插入的內容
* @return 記錄總數
* */
public long linsert(byte[] key, LIST_POSITION where, byte[] pivot,
byte[] value)
{
Jedis jedis = getJedis();
long count = jedis.linsert(key, where, pivot, value);
closeResource(jedis);
return count;
}
/**
* 獲取List中指定位置的值
* @param String key
* @param int index 位置
* @return 值
* **/
public String lindex(String key, int index)
{
return SafeEncoder.encode(lindex(SafeEncoder.encode(key), index));
}
/**
* 獲取List中指定位置的值
* @param byte[] key
* @param int index 位置
* @return 值
* **/
public byte[] lindex(byte[] key, int index)
{
Jedis jedis = getJedis();
byte[] value = jedis.lindex(key, index);
closeResource(jedis);
return value;
}
/**
* 將List中的第一條記錄移出List
* @param String key
* @return 移出的記錄
* */
public String lpop(String key)
{
return SafeEncoder.encode(lpop(SafeEncoder.encode(key)));
}
/**
* 將List中的第一條記錄移出List
* @param byte[] key
* @return 移出的記錄
* */
public byte[] lpop(byte[] key)
{
Jedis jedis = getJedis();
byte[] value = jedis.lpop(key);
closeResource(jedis);
return value;
}
/**
* 將List中最後第一條記錄移出List
*
* @param byte[] key
* @return 移出的記錄
* */
public String rpop(String key)
{
Jedis jedis = getJedis();
String value = jedis.rpop(key);
closeResource(jedis);
return value;
}
/**
* 向List尾部追加記錄
* @param String key
* @param String value
* @return 記錄總數
* */
public long lpush(String key, String value)
{
return lpush(SafeEncoder.encode(key), SafeEncoder.encode(value));
}
/**
* 向List頭部追加記錄
* @param String key
* @param String value
* @return 記錄總數
* */
public long rpush(String key, String value)
{
Jedis jedis = getJedis();
long count = jedis.rpush(key, value);
closeResource(jedis);
return count;
}
/**
* 向List頭部追加記錄
* @param String key
* @param String value
* @return 記錄總數
* */
public long rpush(byte[] key, byte[] value)
{
Jedis jedis = getJedis();
long count = jedis.rpush(key, value);
closeResource(jedis);
return count;
}
/**
* 向List中追加記錄
* @param byte[] key
* @param byte[] value
* @return 記錄總數
* */
public long lpush(byte[] key, byte[] value)
{
Jedis jedis = getJedis();
long count = jedis.lpush(key, value);
closeResource(jedis);
return count;
}
/**
* 獲取指定範圍的記錄,可以做爲分頁使用
* @param String key
* @param long start
* @param long end
* @return List
* */
public List<String> lrange(String key, long start, long end)
{
Jedis jedis = getJedis();
List<String> list = jedis.lrange(key, start, end);
closeResource(jedis);
return list;
}
/**
* 獲取指定範圍的記錄,可以做爲分頁使用
* @param byte[] key
* @param int start
* @param int end 如果爲負數,則尾部開始計算
* @return List
* */
public List<byte[]> lrange(byte[] key, int start, int end)
{
//ShardedJedis jedis = getShardedJedis();
Jedis jedis = getJedis();
List<byte[]> list = jedis.lrange(key, start, end);
closeResource(jedis);
return list;
}
/**
* 刪除List中c條記錄,被刪除的記錄值爲value
* @param byte[] key
* @param int c 要刪除的數量,如果爲負數則從List的尾部檢查並刪除符合的記錄
* @param byte[] value 要匹配的值
* @return 刪除後的List中的記錄數
* */
public long lrem(byte[] key, int c, byte[] value)
{
Jedis jedis = getJedis();
long count = jedis.lrem(key, c, value);
closeResource(jedis);
return count;
}
/**
* 刪除List中c條記錄,被刪除的記錄值爲value
* @param String key
* @param int c 要刪除的數量,如果爲負數則從List的尾部檢查並刪除符合的記錄
* @param String value 要匹配的值
* @return 刪除後的List中的記錄數
* */
public long lrem(String key, int c, String value)
{
return lrem(SafeEncoder.encode(key), c, SafeEncoder.encode(value));
}
/**
* 算是刪除吧,只保留start與end之間的記錄
* @param byte[] key
* @param int start 記錄的開始位置(0表示第一條記錄)
* @param int end 記錄的結束位置(如果爲-1則表示最後一個,-2,-3以此類推)
* @return 執行狀態碼
* */
public String ltrim(byte[] key, int start, int end)
{
Jedis jedis = getJedis();
String str = jedis.ltrim(key, start, end);
closeResource(jedis);
return str;
}
/**
* 算是刪除吧,只保留start與end之間的記錄
* @param String key
* @param int start 記錄的開始位置(0表示第一條記錄)
* @param int end 記錄的結束位置(如果爲-1則表示最後一個,-2,-3以此類推)
* @return 執行狀態碼
* */
public String ltrim(String key, int start, int end)
{
return ltrim(SafeEncoder.encode(key), start, end);
}
}
SerializeUtils:
package com.springboot.exam.controller.redis;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import org.apache.log4j.Logger;
/**
* 序列化:把對象轉換爲字節序列的過程稱爲對象的序列化
* 反序列化:把字節序列恢復爲對象的過程稱爲對象的反序列化
*
* 序列化和反序列化的工具類
* @author jwang
*
*/
public class SerializeUtils
{
private static final Logger LOGGER = Logger.getLogger(SerializeUtils.class);
/**
* 序列化
*
* @param object
* @return
*/
public static byte[] serialize(Object object)
{
ObjectOutputStream objectOutputStream = null;
ByteArrayOutputStream byteArrayOutputStream = null;
try
{
// 序列化
byteArrayOutputStream = new ByteArrayOutputStream();
objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(object);
byte[] bytes = byteArrayOutputStream.toByteArray();
return bytes;
}
catch (Exception e)
{
LOGGER.error("對象序列化失敗!!!");
e.printStackTrace();
}
return null;
}
/**
* 反序列化
*
* @param bytes
* @return
*/
public static Object unserialize(byte[] bytes)
{
ByteArrayInputStream byteArrayInputStream = null;
try
{
// 反序列化
byteArrayInputStream = new ByteArrayInputStream(bytes);
ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
return objectInputStream.readObject();
}
catch (Exception e)
{
LOGGER.error("對象反序列化失敗!!!");
e.printStackTrace();
}
return null;
}
}
導包pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>