java中Redis5大基本型別的用法
阿新 • • 發佈:2019-01-11
redis儲存格式
大家都知道redis支援的儲存型別(String/List/Hash/Set/SortedSet ),但是不一定在工作中都用到過,希望通過整理的這篇文章,讓大家都能知道在java中如何使用redis以及redis對這幾種資料型別的操作。
基本用法
通過Jedis(封裝了redis的Java客戶端)對redis進行操作。
Jedis工具類
public class JedisPoolUtil {
private static Logger logger = Logger.getLogger(JedisPoolUtil.class);
/**
* 連線池
**/
private static JedisPool pool = null;
private static Jedis jedis = null;
static {
//載入配置檔案
InputStream in = JedisPoolUtil.class.getClassLoader().getResourceAsStream("redis.properties");
Properties pro = new Properties();
try {
pro.load(in);
} catch (IOException e) {
e.printStackTrace();
System.out.println("載入檔案失敗");
}
JedisPoolConfig poolConfig = new JedisPoolConfig();
//最大連線數
poolConfig.setMaxTotal(Integer.parseInt(pro.get("redis.maxTotal").toString()));
//最大空閒連線數(控制一個pool最多有多少個狀態為idle(空閒的)的jedis例項)
poolConfig.setMaxIdle(Integer.parseInt(pro.get("redis.maxIdle").toString()));
//最小空閒連線數
poolConfig.setMinIdle(Integer.parseInt(pro.get("redis.minIdle").toString()));
pool = new JedisPool(poolConfig, pro.get("redis.url").toString(), Integer.parseInt(pro.get("redis.port").toString()));
//redis如果設定了密碼:
//pool = new JedisPool(poolConfig, pro.get("redis.url").toString(), Integer.parseInt(pro.get("redis.port").toString()),10000,pro.get("redis.password").toString());
}
/**
* 從jedis連線池中獲取jedis物件
* @return
*/
public static Jedis getJedis() {
return pool.getResource();
}
/**
* 檢測redis是否在執行
* 如果連線正常就返回一個 PONG ,否則返回一個連線錯誤。
*/
public static String ping() {
Jedis jedis = getJedis();
return jedis.ping();
}
/**
* 查詢key的過期時間
* -1, 如果key沒有到期超時。
* -2, 如果鍵不存在。
*
* @return 以秒為單位的時間表示
*/
public static long ttl(String key) {
long len = 0;
try {
jedis = getJedis();
len = jedis.ttl(key);
} catch (Exception e) {
logger.error("Cache時間查詢失敗:" + e);
} finally {
releaseResource(jedis);
}
return len;
}
public static void release(Jedis jedis) {
if (jedis != null) {
jedis.close();
}
}
/**
* 釋放redis資源
*/
@SuppressWarnings("deprecation")
private static void releaseResource(Jedis jedis) {
if (jedis != null) {
pool.returnResource(jedis);
}
}
/**
* 刪除Redis中的所有key
*/
public static void flushAll() {
try {
jedis = getJedis();
jedis.flushAll();
} catch (Exception e) {
logger.error("Cache清空失敗:" + e);
} finally {
releaseResource(jedis);
}
}
/**
* @param seconds 秒
* @Description 儲存一個物件到redis中並指定過期時間
*/
public static Boolean set(String key, String val, int seconds) {
try {
jedis = getJedis();
jedis.set(key, val);
//等於0沒有快取時間
if (seconds != 0) {
jedis.expire(key, seconds);
}
return true;
} catch (Exception e) {
logger.error("Cache儲存失敗:" + e);
return false;
} finally {
releaseResource(jedis);
}
}
/**
* 根據快取鍵獲取Redis快取中的值.
*/
public static String get(String key) {
try {
jedis = getJedis();
String str = jedis.get(key);
return str == null ? null : str;
} catch (Exception e) {
logger.error("Cache獲取失敗:" + e);
return null;
} finally {
releaseResource(jedis);
}
}
/**
* 根據快取鍵清除Redis快取中的值.
*/
public static Boolean del(String key) {
try {
jedis = getJedis();
jedis.del(key);
return true;
} catch (Exception e) {
logger.error("Cache刪除失敗:" + e);
return false;
} finally {
releaseResource(jedis);
}
}
/**
* @param key
* @param seconds 超時時間(單位為秒)
* @return
*/
public static Boolean expire(String key, int seconds) {
try {
jedis = getJedis();
jedis.expire(key, seconds);
return true;
} catch (Exception e) {
logger.error("Cache設定超時時間失敗:" + e);
return false;
} finally {
releaseResource(jedis);
}
}
/**
* 判斷一個key是否存在
*/
public static Boolean exists(String key) {
Boolean result = false;
try {
jedis = getJedis();
result = jedis.exists(key);
return result;
} catch (Exception e) {
logger.error("Cache獲取失敗:" + e);
return false;
} finally {
releaseResource(jedis);
}
}
}
redis配置檔案
#最大連線數
redis.maxTotal=100
#最大空閒連線數
redis.maxIdle=30
#最小空閒連線數
redis.minIdle=10
#連線地址
redis.url=127.0.0.1
#埠號
redis.port=6379
String測試
public class StringTest {
public Jedis jedis = JedisPoolUtil.getJedis();
/**
* 新增和獲取
*/
@Test
public void add() {
jedis.set("name","yswKnight");
System.out.println(jedis.get("name"));//yswKnight
}
/**
* 刪除值
*/
@Test
public void del() {
jedis.del("name");
System.out.println(jedis.exists("name"));//false
}
/**
* 自減
*/
@Test
public void decrease() {
jedis.set("num","1");
System.out.println(jedis.get("num"));
jedis.decr("num");
System.out.println(jedis.get("num"));//0
}
/**
* 自加
*/
@Test
public void increase(){
jedis.set("num","1");
System.out.println(jedis.get("num"));
jedis.incr("num");
jedis.incr("num");
System.out.println(jedis.get("num"));//3
}
/**
* 加上一個數
* incrBy 返回的是修改之後的值如果原值是字串不是數字,則會丟擲異常
*/
@Test
public void increaseBy(){
jedis.set("num","1");
System.out.println(jedis.get("num"));
jedis.incrBy("num",7);
System.out.println(jedis.get("num"));//8
}
/**
* 減去一個數
*/
@Test
public void decreaseBy(){
jedis.set("num","7");
System.out.println(jedis.get("num"));
jedis.decrBy("num",3);
System.out.println(jedis.get("num"));//4
}
/**
* 字串拼接
*/
@Test
public void append () {
jedis.set("name","Lebron");
System.out.println(jedis.get("name"));
Long len = jedis.append("name", "James");
System.out.println(len);//11
System.out.println(jedis.get("name"));//LebronJames
}
}
List測試
public class ListTest {
public Jedis jedis = JedisPoolUtil.getJedis();
@Test
public void testList(){
jedis.flushDB();
System.out.println("===========新增一個list===========");
/**
* lpush 新增元素
*/
jedis.lpush("collections", "ArrayList", "Vector", "Stack", "HashMap", "WeakHashMap", "LinkedHashMap");
jedis.lpush("collections", "HashSet");
jedis.lpush("collections", "TreeSet");
jedis.lpush("collections", "TreeMap");
/**
* lrange 根據索引區間來獲取值(-1代表倒數第一個元素,-2代表倒數第二個元素)
*/
System.out.println("collections的內容:"+jedis.lrange("collections", 0, -1));//[TreeMap, TreeSet, HashSet, LinkedHashMap, WeakHashMap, HashMap, Stack, Vector, ArrayList]
System.out.println("collections區間0-3的元素:"+jedis.lrange("collections",0,3));//[TreeMap, TreeSet, HashSet, LinkedHashMap]
System.out.println("===============================");
/**
* lrem 刪除列表指定的值,第二個引數為刪除的個數(有重複時),後add進去的值先被刪,類似於出棧
*/
System.out.println("刪除指定元素個數:"+jedis.lrem("collections", 2, "HashMap"));//1
System.out.println("collections的內容:"+jedis.lrange("collections", 0, -1));//[TreeMap, TreeSet, HashSet, LinkedHashMap, WeakHashMap, Stack, Vector, ArrayList]
/**
* ltrim 刪除索引區間之外的元素
*/
System.out.println("刪除下表0-3區間之外的元素:"+jedis.ltrim("collections", 0, 3));//OK
System.out.println("collections的內容:"+jedis.lrange("collections", 0, -1));//[TreeMap, TreeSet, HashSet, LinkedHashMap]
/**
* lpop 移除並返回列表 key 的頭元素。
*/
System.out.println("collections列表出棧(左端):"+jedis.lpop("collections"));//TreeMap
System.out.println("collections的內容:"+jedis.lrange("collections", 0, -1));//[TreeSet, HashSet, LinkedHashMap]
/**
* rpush 新增元素,從列表右端,與lpush相對應
*/
System.out.println("collections新增元素,從列表右端,與lpush相對應:"+jedis.rpush("collections", "EnumMap"));//4
System.out.println("collections的內容:"+jedis.lrange("collections", 0, -1));//[TreeSet, HashSet, LinkedHashMap, EnumMap]
/**
* rpop 移除並返回列表 key 的尾元素。
*/
System.out.println("collections列表出棧(右端):"+jedis.rpop("collections"));//EnumMap
System.out.println("collections的內容:"+jedis.lrange("collections", 0, -1));//[TreeSet, HashSet, LinkedHashMap]
/**
* lset 修改 key 指定下標 index 的內容
*/
System.out.println("修改collections指定下標1的內容:"+jedis.lset("collections", 1, "LinkedArrayList"));//OK
System.out.println("collections的內容:"+jedis.lrange("collections", 0, -1));//[TreeSet, LinkedArrayList, LinkedHashMap]
System.out.println("===============================");
/**
* llen 返回 key 的長度
*/
System.out.println("collections的長度:"+jedis.llen("collections"));//3
/**
* lindex 獲取 key 下標為 index 的元素
*/
System.out.println("獲取collections下標為2的元素:"+jedis.lindex("collections", 2));//LinkedHashMap
System.out.println("===============================");
/**
* 新增數字元素
*/
jedis.lpush("sortedList", "3","6","2","0","7","4");
System.out.println("sortedList排序前:"+jedis.lrange("sortedList", 0, -1));//[4, 7, 0, 2, 6, 3]
/**
* 對 key 裡的整數型元素進行排序
*/
System.out.println("sortedList排序後:"+jedis.sort("sortedList"));//[0, 2, 3, 4, 6, 7]
}
}
Set測試
Set集合,和List類的區別就是:
set中不會出現重複的資料,他可以進行聚合操作效率比較高。
其餘的操作基本上和list相同
/**
* Set集合,和List類的區別就是:
* set中不會出現重複的資料
* 他可以進行聚合操作效率比較高
* 其餘的操作基本上和list相同
*/
public class SetTest {
public Jedis jedis = JedisPoolUtil.getJedis();
/**
* 新增元素刪除元素
*/
@Test
public void sadd(){
Long num = jedis.sadd("myset", "a",