關于Redis
在正式分析題目的問題之前,我們先來聊聊Redis的基礎知識。
基于鍵值對的存儲系統 :字典形式。
五種資料結構:字元串(String),Hash(字典),清單(List),集合(Set),有序集合(Sorted Set)。
Redis大部分時間用來做緩存,因為速度快(記憶體資料庫,單線程,單程序,Redis 6.0支援多線程,後面我們會詳細講Redis 6.0的新特性 )。
Redis的使用場景
- 做緩存:String類型最多,其次是hash(字典),value值使用的最多的是json格式。
- 計數(自增):點贊數,點踩數,通路數,全局計數等。
- 消息隊列:清單類型,先進先出或者先進後出,bloop。這個可以參考我寫的一個開源架構,位址為: https://github.com/sunshinelyz/mykit-delay 。
- 釋出訂閱(觀察者模式)
- 排行榜:有序集合
- 分布式鎖:可以關注【冰河技術】微信公衆号,參考我寫的《 【高并發】高并發分布式鎖架構解密,不是所有的鎖都是分布式鎖!! 》,也可以參考我寫的一個分布式鎖插件,連結位址為: https://github.com/sunshinelyz/mykit-lock
- 做附近的人
- 布隆過濾器
- 統計線上人數(Bitmap)等等
以下使用場景也是5大資料類型中的一種:
- BitMaps位圖:布隆過濾器 本質是字元串
- HyperLogLog:超小記憶體唯一值計數,12kb HyperLogLog 本質是 字元串
- GEO:地理資訊定位 本質是有序集合
主從複制: 主伺服器和從伺服器,Redis中的資料可以從主伺服器同步到從伺服器上。
高可用和分布式:
- 2.8版本以後使用redis-sentinel支援高可用(做哨兵)
- 3.0版本以後支援分布式
五大資料類型
String(字元串)
string類型是二進制安全的。意思是redis的string可以包含任何資料。比如jpg圖檔或者序列化的對象 。
string類型是Redis最基本的資料類型,一個redis中字元串value最多可以是512M。
Hash(哈希)
Redis hash 是一個鍵值對集合。Redis hash是一個string類型的field和value的映射表,hash特别适合用于存儲對象。類似Java裡面的Map<String,Object>
List(清單)
Redis 清單是簡單的字元串清單,按照插入順序排序。你可以添加一個元素導清單的頭部(左邊)或者尾部(右邊)。底層實際是個連結清單。
Set(集合)
Redis的Set是string類型的無序集合。它是通過HashTable實作的。
Zset(sorted set:有序集合)
Redis zset 和 set 一樣也是string類型元素的集合,且不允許重複的成員。不同的是每個元素都會關聯一個double類型的分數。Redis正是通過分數來為集合中的成員進行從小到大的排序。zset的成員是唯一的,但分數(score)卻可以重複。
使用案例
這裡,為了讓小夥伴們更加清晰的了解如何使用Java用戶端來操作Redis資料,我們會分别使用Jedis和JedisCluster來示範如何操作Redis中的資料。
準備工作
通過maven引入Jedis的依賴包。
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
Jedis的使用
建立Jedis對象,set方法存儲key-value值,get方法擷取key對應的值。主要是用于單個redis。
Jedis jedis = new Jedis("192.168.175.100", 6379);
jedis.set("Jedis", "Hello Work!");
System.out.println(jedis.get("Jedis"));
jedis.close()
這裡是使用IDEA編輯器對Jedis類結構的一個關系圖,從圖中看出Jedis繼承BinaryJedis,實作多個接口。
每一個接口都代表了一類Redis指令,例如JedisCommands中包含了SET GET等指令,MultiKeyCommands中包含了針對多個Key的MSET MGET等指令。
接下來,我們給出Jedis測試Redis五大資料類型的完整測試代碼。
package com.redis;
import org.junit.Test;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.SortingParams;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
/**
* 單機環境Redis操作:一台Redis伺服器
*/
public class Standalone {
private static Jedis jedis;
static {
jedis = new Jedis("192.168.56.180", 6379);
jedis.auth("123456"); // 之前我在redis配置中配置了權限密碼,這裡需要設定
}
/**
* 測試key - value 的資料
* @throws InterruptedException
*/
@Test
public void testKey() throws InterruptedException {
System.out.println("清空資料:"+jedis.flushDB());
System.out.println("判斷某個鍵是否存在:"+jedis.exists("username"));
System.out.println("新增<'username','wukong'>的鍵值對:"+jedis.set("username", "wukong"));
System.out.println("是否存在:"+jedis.exists("name"));
System.out.println("新增<'password','password'>的鍵值對:"+jedis.set("password", "password"));
Set<String> keys = jedis.keys("*");
System.out.println("系統中所有的鍵如下:"+keys);
System.out.println("删除鍵password:"+jedis.del("password"));
System.out.println("判斷鍵password是否存在:"+jedis.exists("password"));
System.out.println("設定鍵username的過期時間為5s:"+jedis.expire("username", 5));
TimeUnit.SECONDS.sleep(2);
System.out.println("檢視鍵username的剩餘生存時間:"+jedis.ttl("username"));
System.out.println("移除鍵username的生存時間:"+jedis.persist("username"));
System.out.println("檢視鍵username的剩餘生存時間:"+jedis.ttl("username"));
System.out.println("檢視鍵username所存儲的值的類型:"+jedis.type("username"));
}
/***
* 字元串操作
* memcached和redis同樣有append的操作,但是memcached有prepend的操作,redis中并沒有。
* @throws InterruptedException
*/
@Test
public void testString() throws InterruptedException {
jedis.flushDB();
System.out.println("===========增加資料===========");
System.out.println(jedis.set("key1","value1"));
System.out.println(jedis.set("key2","value2"));
System.out.println(jedis.set("key3", "value3"));
System.out.println("删除鍵key2:"+jedis.del("key2"));
System.out.println("擷取鍵key2:"+jedis.get("key2"));
System.out.println("修改key1:"+jedis.set("key1", "value1Changed"));
System.out.println("擷取key1的值:"+jedis.get("key1"));
System.out.println("在key3後面加入值:"+jedis.append("key3", "End"));
System.out.println("key3的值:"+jedis.get("key3"));
System.out.println("增加多個鍵值對:"+jedis.mset("key01","value01","key02","value02","key03","value03"));
System.out.println("擷取多個鍵值對:"+jedis.mget("key01","key02","key03"));
System.out.println("擷取多個鍵值對:"+jedis.mget("key01","key02","key03","key04"));
System.out.println("删除多個鍵值對:"+jedis.del(new String[]{"key01","key02"}));
System.out.println("擷取多個鍵值對:"+jedis.mget("key01","key02","key03"));
jedis.flushDB();
System.out.println("===========新增鍵值對防止覆寫原先值==============");
System.out.println(jedis.setnx("key1", "value1"));
System.out.println(jedis.setnx("key2", "value2"));
System.out.println(jedis.setnx("key2", "value2-new"));
System.out.println(jedis.get("key1"));
System.out.println(jedis.get("key2"));
System.out.println("===========新增鍵值對并設定有效時間=============");
System.out.println(jedis.setex("key3", 2, "value3"));
System.out.println(jedis.get("key3"));
TimeUnit.SECONDS.sleep(3);
System.out.println(jedis.get("key3"));
System.out.println("===========擷取原值,更新為新值==========");//GETSET is an atomic set this value and return the old value command.
System.out.println(jedis.getSet("key2", "key2GetSet"));
System.out.println(jedis.get("key2"));
System.out.println("獲得key2的值的字串:"+jedis.getrange("key2", 2, 4));
}
/***
* 整數和浮點數
*/
@Test
public void testNumber() {
jedis.flushDB();
jedis.set("key1", "1");
jedis.set("key2", "2");
jedis.set("key3", "2.3");
System.out.println("key1的值:"+jedis.get("key1"));
System.out.println("key2的值:"+jedis.get("key2"));
System.out.println("key1的值加1:"+jedis.incr("key1"));
System.out.println("擷取key1的值:"+jedis.get("key1"));
System.out.println("key2的值減1:"+jedis.decr("key2"));
System.out.println("擷取key2的值:"+jedis.get("key2"));
System.out.println("将key1的值加上整數5:"+jedis.incrBy("key1", 5));
System.out.println("擷取key1的值:"+jedis.get("key1"));
System.out.println("将key2的值減去整數5:"+jedis.decrBy("key2", 5));
System.out.println("擷取key2的值:"+jedis.get("key2"));
}
/***
* 清單
*/
@Test
public void testList() {
jedis.flushDB();
System.out.println("===========添加一個list===========");
jedis.lpush("collections", "ArrayList", "Vector", "Stack", "HashMap", "WeakHashMap", "LinkedHashMap");
jedis.lpush("collections", "HashSet");
jedis.lpush("collections", "TreeSet");
jedis.lpush("collections", "TreeMap");
System.out.println("collections的内容:"+jedis.lrange("collections", 0, -1));//-1代表倒數第一個元素,-2代表倒數第二個元素
System.out.println("collections區間0-3的元素:"+jedis.lrange("collections",0,3));
System.out.println("===============================");
// 删除清單指定的值 ,第二個參數為删除的個數(有重複時),後add進去的值先被删,類似于出棧
System.out.println("删除指定元素個數:"+jedis.lrem("collections", 2, "HashMap"));
System.out.println("collections的内容:"+jedis.lrange("collections", 0, -1));
System.out.println("删除下表0-3區間之外的元素:"+jedis.ltrim("collections", 0, 3));
System.out.println("collections的内容:"+jedis.lrange("collections", 0, -1));
System.out.println("collections清單出棧(左端):"+jedis.lpop("collections"));
System.out.println("collections的内容:"+jedis.lrange("collections", 0, -1));
System.out.println("collections添加元素,從清單右端,與lpush相對應:"+jedis.rpush("collections", "EnumMap"));
System.out.println("collections的内容:"+jedis.lrange("collections", 0, -1));
System.out.println("collections清單出棧(右端):"+jedis.rpop("collections"));
System.out.println("collections的内容:"+jedis.lrange("collections", 0, -1));
System.out.println("修改collections指定下标1的内容:"+jedis.lset("collections", 1, "LinkedArrayList"));
System.out.println("collections的内容:"+jedis.lrange("collections", 0, -1));
System.out.println("===============================");
System.out.println("collections的長度:"+jedis.llen("collections"));
System.out.println("擷取collections下标為2的元素:"+jedis.lindex("collections", 2));
System.out.println("===============================");
jedis.lpush("sortedList", "3","6","2","0","7","4");
System.out.println("sortedList排序前:"+jedis.lrange("sortedList", 0, -1));
System.out.println(jedis.sort("sortedList"));
System.out.println("sortedList排序後:"+jedis.lrange("sortedList", 0, -1));
}
/***
* set集合
*/
@Test
public void testSet() {
jedis.flushDB();
System.out.println("============向集合中添加元素============");
System.out.println(jedis.sadd("eleSet", "e1","e2","e4","e3","e0","e8","e7","e5"));
System.out.println(jedis.sadd("eleSet", "e6"));
System.out.println(jedis.sadd("eleSet", "e6"));
System.out.println("eleSet的所有元素為:"+jedis.smembers("eleSet"));
System.out.println("删除一個元素e0:"+jedis.srem("eleSet", "e0"));
System.out.println("eleSet的所有元素為:"+jedis.smembers("eleSet"));
System.out.println("删除兩個元素e7和e6:"+jedis.srem("eleSet", "e7","e6"));
System.out.println("eleSet的所有元素為:"+jedis.smembers("eleSet"));
System.out.println("随機的移除集合中的一個元素:"+jedis.spop("eleSet"));
System.out.println("随機的移除集合中的一個元素:"+jedis.spop("eleSet"));
System.out.println("eleSet的所有元素為:"+jedis.smembers("eleSet"));
System.out.println("eleSet中包含元素的個數:"+jedis.scard("eleSet"));
System.out.println("e3是否在eleSet中:"+jedis.sismember("eleSet", "e3"));
System.out.println("e1是否在eleSet中:"+jedis.sismember("eleSet", "e1"));
System.out.println("e1是否在eleSet中:"+jedis.sismember("eleSet", "e5"));
System.out.println("=================================");
System.out.println(jedis.sadd("eleSet1", "e1","e2","e4","e3","e0","e8","e7","e5"));
System.out.println(jedis.sadd("eleSet2", "e1","e2","e4","e3","e0","e8"));
System.out.println("将eleSet1中删除e1并存入eleSet3中:"+jedis.smove("eleSet1", "eleSet3", "e1"));
System.out.println("将eleSet1中删除e2并存入eleSet3中:"+jedis.smove("eleSet1", "eleSet3", "e2"));
System.out.println("eleSet1中的元素:"+jedis.smembers("eleSet1"));
System.out.println("eleSet3中的元素:"+jedis.smembers("eleSet3"));
System.out.println("============集合運算=================");
System.out.println("eleSet1中的元素:"+jedis.smembers("eleSet1"));
System.out.println("eleSet2中的元素:"+jedis.smembers("eleSet2"));
System.out.println("eleSet1和eleSet2的交集:"+jedis.sinter("eleSet1","eleSet2"));
System.out.println("eleSet1和eleSet2的并集:"+jedis.sunion("eleSet1","eleSet2"));
System.out.println("eleSet1和eleSet2的差集:"+jedis.sdiff("eleSet1","eleSet2"));//eleSet1中有,eleSet2中沒有
}
/***
* 散列
*/
@Test
public void testHash() {
jedis.flushDB();
Map<String,String> map = new HashMap<String,String>();
map.put("key1","value1");
map.put("key2","value2");
map.put("key3","value3");
map.put("key4","value4");
jedis.hmset("hash",map);
jedis.hset("hash", "key5", "value5");
System.out.println("散列hash的所有鍵值對為:"+jedis.hgetAll("hash"));//return Map<String,String>
System.out.println("散列hash的所有鍵為:"+jedis.hkeys("hash"));//return Set<String>
System.out.println("散列hash的所有值為:"+jedis.hvals("hash"));//return List<String>
System.out.println("将key6儲存的值加上一個整數,如果key6不存在則添加key6:"+jedis.hincrBy("hash", "key6", 6));
System.out.println("散列hash的所有鍵值對為:"+jedis.hgetAll("hash"));
System.out.println("将key6儲存的值加上一個整數,如果key6不存在則添加key6:"+jedis.hincrBy("hash", "key6", 3));
System.out.println("散列hash的所有鍵值對為:"+jedis.hgetAll("hash"));
System.out.println("删除一個或者多個鍵值對:"+jedis.hdel("hash", "key2"));
System.out.println("散列hash的所有鍵值對為:"+jedis.hgetAll("hash"));
System.out.println("散列hash中鍵值對的個數:"+jedis.hlen("hash"));
System.out.println("判斷hash中是否存在key2:"+jedis.hexists("hash","key2"));
System.out.println("判斷hash中是否存在key3:"+jedis.hexists("hash","key3"));
System.out.println("擷取hash中的值:"+jedis.hmget("hash","key3"));
System.out.println("擷取hash中的值:"+jedis.hmget("hash","key3","key4"));
}
/**
* 有序集合
*/
@Test
public void testSortedSet() {
jedis.flushDB();
Map<String,Double> map = new HashMap<String,Double>();
map.put("key2",1.2);
map.put("key3",4.0);
map.put("key4",5.0);
map.put("key5",0.2);
System.out.println(jedis.zadd("zset", 3,"key1"));
System.out.println(jedis.zadd("zset",map));
System.out.println("zset中的所有元素:"+jedis.zrange("zset", 0, -1));
System.out.println("zset中的所有元素:"+jedis.zrangeWithScores("zset", 0, -1));
System.out.println("zset中的所有元素:"+jedis.zrangeByScore("zset", 0,100));
System.out.println("zset中的所有元素:"+jedis.zrangeByScoreWithScores("zset", 0,100));
System.out.println("zset中key2的分值:"+jedis.zscore("zset", "key2"));
System.out.println("zset中key2的排名:"+jedis.zrank("zset", "key2"));
System.out.println("删除zset中的元素key3:"+jedis.zrem("zset", "key3"));
System.out.println("zset中的所有元素:"+jedis.zrange("zset", 0, -1));
System.out.println("zset中元素的個數:"+jedis.zcard("zset"));
System.out.println("zset中分值在1-4之間的元素的個數:"+jedis.zcount("zset", 1, 4));
System.out.println("key2的分值加上5:"+jedis.zincrby("zset", 5, "key2"));
System.out.println("key3的分值加上4:"+jedis.zincrby("zset", 4, "key3"));
System.out.println("zset中的所有元素:"+jedis.zrange("zset", 0, -1));
}
/**
* 排序
*/
@Test
public void testSort()
{
jedis.flushDB();
jedis.lpush("collections", "ArrayList", "Vector", "Stack", "HashMap", "WeakHashMap", "LinkedHashMap");
System.out.println("collections的内容:"+jedis.lrange("collections", 0, -1));
SortingParams sortingParameters = new SortingParams();
System.out.println(jedis.sort("collections",sortingParameters.alpha()));
System.out.println("===============================");
jedis.lpush("sortedList", "3","6","2","0","7","4");
System.out.println("sortedList排序前:"+jedis.lrange("sortedList", 0, -1));
System.out.println("升序:"+jedis.sort("sortedList", sortingParameters.asc()));
System.out.println("升序:"+jedis.sort("sortedList", sortingParameters.desc()));
System.out.println("===============================");
jedis.lpush("userlist", "33");
jedis.lpush("userlist", "22");
jedis.lpush("userlist", "55");
jedis.lpush("userlist", "11");
jedis.hset("user:66", "name", "66");
jedis.hset("user:55", "name", "55");
jedis.hset("user:33", "name", "33");
jedis.hset("user:22", "name", "79");
jedis.hset("user:11", "name", "24");
jedis.hset("user:11", "add", "beijing");
jedis.hset("user:22", "add", "shanghai");
jedis.hset("user:33", "add", "guangzhou");
jedis.hset("user:55", "add", "chongqing");
jedis.hset("user:66", "add", "xi'an");
sortingParameters = new SortingParams();
sortingParameters.get("user:*->name");
sortingParameters.get("user:*->add");
System.out.println(jedis.sort("userlist",sortingParameters));
}
}
JedisCluster的使用
JedisCluster類圖和jedis類圖大緻一樣,不過jedisCluster有一些指令是不可用的。比如BinaryJedisCluster類被廢棄的指令。主要是用在叢集中。
接下來,我們給出使用JedisCluster測試Redis五大資料類型的完整源碼。
package com.redis;
import org.junit.Test;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.SortingParams;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* 叢集環境下Jedis操作
*/
public class Cluster {
private static JedisCluster jedis;
static {
// 添加叢集的服務節點Set集合
Set<HostAndPort> hostAndPortsSet = new HashSet<HostAndPort>();
// 添加節點
hostAndPortsSet.add(new HostAndPort("192.168.56.180", 7777));
hostAndPortsSet.add(new HostAndPort("192.168.56.180", 8888));
hostAndPortsSet.add(new HostAndPort("192.168.56.181", 7777));
hostAndPortsSet.add(new HostAndPort("192.168.56.181", 8888));
hostAndPortsSet.add(new HostAndPort("192.168.56.182", 7777));
hostAndPortsSet.add(new HostAndPort("192.168.56.182", 8888));
// Jedis連接配接池配置
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
// 最大空閑連接配接數, 預設8個
jedisPoolConfig.setMaxIdle(100);
// 最大連接配接數, 預設8個
jedisPoolConfig.setMaxTotal(500);
//最小空閑連接配接數, 預設0
jedisPoolConfig.setMinIdle(0);
// 擷取連接配接時的最大等待毫秒數(如果設定為阻塞時BlockWhenExhausted),如果逾時就抛異常, 小于零:阻塞不确定的時間, 預設-1
jedisPoolConfig.setMaxWaitMillis(2000); // 設定2秒
//對拿到的connection進行validateObject校驗
jedisPoolConfig.setTestOnBorrow(true);
jedis = new JedisCluster(hostAndPortsSet, jedisPoolConfig);
}
/**
* 測試key:value資料
* 叢集中flushDB、keys廢棄
*/
@Test
public void testKey() throws InterruptedException {
//System.out.println("清空資料:"+jedis.flushDB());
System.out.println("判斷某個鍵是否存在:"+jedis.exists("username"));
System.out.println("新增<'username','wukong'>的鍵值對:"+jedis.set("username", "xiaohai"));
System.out.println("是否存在:"+jedis.exists("username"));
System.out.println("新增<'password','password'>的鍵值對:"+jedis.set("password", "123456"));
//Set<String> keys = jedis.keys("*");
// System.out.println("系統中所有的鍵如下:"+keys);
System.out.println("删除鍵password:"+jedis.del("password"));
System.out.println("判斷鍵password是否存在:"+jedis.exists("password"));
System.out.println("設定鍵username的過期時間為10s:"+jedis.expire("username", 10));
TimeUnit.SECONDS.sleep(2); // 線程睡眠2秒System.out.println("檢視鍵username的剩餘生存時間:"+jedis.ttl("username"));
System.out.println("檢視鍵username的剩餘生存時間:"+jedis.ttl("username"));
System.out.println("移除鍵username的生存時間:"+jedis.persist("username"));
System.out.println("檢視鍵username的剩餘生存時間:"+jedis.ttl("username"));
System.out.println("檢視鍵username所存儲的值的類型:"+jedis.type("username"));
}
/***
* 字元串操作
* memcached和redis同樣有append的操作,但是memcached有prepend的操作,redis中并沒有。
* 叢集中flushDB、keys、del(多個值)、mset(多個值)廢棄
* @throws InterruptedException
*/
@Test
public void testString() throws InterruptedException {
//jedis.flushDB();
System.out.println("===========增加資料===========");
System.out.println(jedis.set("key1","value1"));
System.out.println(jedis.set("key2","value2"));
System.out.println(jedis.set("key3", "value3"));
System.out.println("删除鍵key2:"+jedis.del("key2"));
System.out.println("擷取鍵key2:"+jedis.get("key2"));
System.out.println("修改key1:"+jedis.set("key1", "value1Changed"));
System.out.println("擷取key1的值:"+jedis.get("key1"));
System.out.println("在key3後面加入值:"+jedis.append("key3", "End"));
System.out.println("key3的值:"+jedis.get("key3"));
//指令的時候才會去連接配接連接配接,叢集中連接配接是對一個節點連接配接,不能判斷多個key經過crc16算法所對應的槽在一個節點上,不支援多key擷取、删除
//System.out.println("增加多個鍵值對:"+jedis.mset("key01","value01","key02","value02"));
//System.out.println("擷取多個鍵值對:"+jedis.mget("key01","key02","key03"));
//System.out.println("擷取多個鍵值對:"+jedis.mget("key01","key02","key03","key04"));
//System.out.println("删除多個鍵值對:"+jedis.del(new String[]{"key01","key02"}));
//System.out.println("擷取多個鍵值對:"+jedis.mget("key01","key02","key03"));
//jedis.flushDB();
System.out.println("===========新增鍵值對防止覆寫原先值==============");
System.out.println(jedis.setnx("key1", "value1"));
System.out.println(jedis.setnx("key2", "value2"));
System.out.println(jedis.setnx("key2", "value2-new"));
System.out.println(jedis.get("key1"));
System.out.println(jedis.get("key2"));
System.out.println("===========新增鍵值對并設定有效時間=============");
System.out.println(jedis.setex("key3", 2, "value3"));
System.out.println(jedis.get("key3"));
TimeUnit.SECONDS.sleep(3);
System.out.println(jedis.get("key3"));
System.out.println("===========擷取原值,更新為新值==========");//GETSET is an atomic set this value and return the old value command.
System.out.println(jedis.getSet("key2", "key2GetSet"));
System.out.println(jedis.get("key2"));
System.out.println("獲得key2的值的字串:"+jedis.getrange("key2", 2, 4)); // 相當截取字元串的第二個位置-第四個位置的字元串
}
/***
* 整數和浮點數
*/
@Test
public void testNumber() {
jedis.set("key1", "1");
jedis.set("key2", "2");
jedis.set("key3", "2.3");
System.out.println("key1的值:"+jedis.get("key1"));
System.out.println("key2的值:"+jedis.get("key2"));
System.out.println("key1的值加1:"+jedis.incr("key1"));
System.out.println("擷取key1的值:"+jedis.get("key1"));
System.out.println("key2的值減1:"+jedis.decr("key2"));
System.out.println("擷取key2的值:"+jedis.get("key2"));
System.out.println("将key1的值加上整數5:"+jedis.incrBy("key1", 5));
System.out.println("擷取key1的值:"+jedis.get("key1"));
System.out.println("将key2的值減去整數5:"+jedis.decrBy("key2", 5));
System.out.println("擷取key2的值:"+jedis.get("key2"));
System.out.println("key3的值:"+jedis.get("key3"));
// 這裡會報錯,因為key3不是整數不能做計算:redis.clients.jedis.exceptions.JedisDataException: ERR value is not an integer or out of range
// System.out.println("key2的值減1:"+jedis.decr("key3"));
}
/***
* 清單
*/
@Test
public void testList() {
System.out.println("===========添加一個list===========");
jedis.lpush("collections", "ArrayList", "Vector", "Stack", "HashMap", "WeakHashMap", "LinkedHashMap");
jedis.lpush("collections", "HashSet"); // 疊加
jedis.lpush("collections", "TreeSet"); // 疊加
jedis.lpush("collections", "TreeMap"); // 疊加
System.out.println("collections的内容:"+jedis.lrange("collections", 0, -1));//-1代表倒數第一個元素,-2代表倒數第二個元素
System.out.println("collections區間0-3的元素:"+jedis.lrange("collections",0,3)); // 前面4個值
System.out.println("===============================");
// 删除清單指定的值 ,第二個參數為删除的個數(有重複時),後add進去的值先被删,類似于出棧
System.out.println("删除指定元素個數:"+jedis.lrem("collections", 2, "HashMap"));
System.out.println("collections的内容:"+jedis.lrange("collections", 0, -1));
System.out.println("删除下表0-3區間之外的元素:"+jedis.ltrim("collections", 0, 3));
System.out.println("collections的内容:"+jedis.lrange("collections", 0, -1));
System.out.println("collections清單出棧(左端):"+jedis.lpop("collections"));
System.out.println("collections的内容:"+jedis.lrange("collections", 0, -1));
System.out.println("collections添加元素,從清單右端,與lpush相對應:"+jedis.rpush("collections", "EnumMap"));
System.out.println("collections的内容:"+jedis.lrange("collections", 0, -1));
System.out.println("collections清單出棧(右端):"+jedis.rpop("collections"));
System.out.println("collections的内容:"+jedis.lrange("collections", 0, -1));
System.out.println("修改collections指定下标1的内容:"+jedis.lset("collections", 1, "LinkedArrayList"));
System.out.println("collections的内容:"+jedis.lrange("collections", 0, -1));
System.out.println("===============================");
System.out.println("collections的長度:"+jedis.llen("collections"));
System.out.println("擷取collections下标為2的元素:"+jedis.lindex("collections", 2));
System.out.println("===============================");
jedis.lpush("sortedList", "3","6","2","0","7","4");
System.out.println("sortedList排序前:"+jedis.lrange("sortedList", 0, -1));
System.out.println(jedis.sort("sortedList"));
System.out.println("sortedList排序後:"+jedis.lrange("sortedList", 0, -1));
}
/***
* set集合
*/
@Test
public void testSet() {
System.out.println("============向集合中添加元素============");
System.out.println(jedis.sadd("eleSet", "e1","e2","e4","e3","e0","e8","e7","e5"));
System.out.println(jedis.sadd("eleSet", "e6"));
System.out.println(jedis.sadd("eleSet", "e6")); // 傳回0,集合中已經存在
System.out.println("eleSet的所有元素為:"+jedis.smembers("eleSet"));
System.out.println("删除一個元素e0:"+jedis.srem("eleSet", "e0"));
System.out.println("eleSet的所有元素為:"+jedis.smembers("eleSet"));
System.out.println("删除兩個元素e7和e6:"+jedis.srem("eleSet", "e7","e6"));
System.out.println("eleSet的所有元素為:"+jedis.smembers("eleSet"));
System.out.println("随機的移除集合中的一個元素:"+jedis.spop("eleSet"));
System.out.println("随機的移除集合中的一個元素:"+jedis.spop("eleSet"));
System.out.println("eleSet的所有元素為:"+jedis.smembers("eleSet"));
System.out.println("eleSet中包含元素的個數:"+jedis.scard("eleSet"));
System.out.println("e3是否在eleSet中:"+jedis.sismember("eleSet", "e3"));
System.out.println("e1是否在eleSet中:"+jedis.sismember("eleSet", "e1"));
System.out.println("e5是否在eleSet中:"+jedis.sismember("eleSet", "e5"));
// 叢集下并存會報錯:redis.clients.jedis.exceptions.JedisClusterException: No way to dispatch this command to Redis Cluster because keys have different slots.
// Redis叢集,從key1集合與key2集合并存、交集、差集,兩個鍵經過crc16算法可能有不同的槽。
/*System.out.println("=================================");
System.out.println(jedis.sadd("eleSet1", "e1","e2","e4","e3","e0","e8","e7","e5"));
System.out.println(jedis.sadd("eleSet2", "e1","e2","e4","e3","e0","e8"));
System.out.println("将eleSet1中删除e1并存入eleSet3中:"+jedis.smove("eleSet1", "eleSet3", "e1"));
System.out.println("将eleSet1中删除e2并存入eleSet3中:"+jedis.smove("eleSet1", "eleSet3", "e2"));
System.out.println("eleSet1中的元素:"+jedis.smembers("eleSet1"));
System.out.println("eleSet3中的元素:"+jedis.smembers("eleSet3"));*/
/*System.out.println("============集合運算=================");
System.out.println("eleSet1中的元素:"+jedis.smembers("eleSet1"));
System.out.println("eleSet2中的元素:"+jedis.smembers("eleSet2"));
System.out.println("eleSet1和eleSet2的交集:"+jedis.sinter("eleSet1","eleSet2"));
System.out.println("eleSet1和eleSet2的并集:"+jedis.sunion("eleSet1","eleSet2"));
System.out.println("eleSet1和eleSet2的差集:"+jedis.sdiff("eleSet1","eleSet2"));*/
jedis.del("eleSet");
jedis.del("eleSet1");
jedis.del("eleSet2");
jedis.del("eleSet3");
}
/***
* 散列
*/
@Test
public void testHash() {
Map<String,String> map = new HashMap<String,String>();
map.put("key1","value1");
map.put("key2","value2");
map.put("key3","value3");
map.put("key4","value4");
jedis.hmset("hash",map);
jedis.hset("hash", "key5", "value5");
System.out.println("散列hash的所有鍵值對為:"+jedis.hgetAll("hash"));//return Map<String,String>
System.out.println("散列hash的所有鍵為:"+jedis.hkeys("hash"));//return Set<String>
System.out.println("散列hash的所有值為:"+jedis.hvals("hash"));//return List<String>
System.out.println("将key6儲存的值加上一個整數,如果key6不存在則添加key6:"+jedis.hincrBy("hash", "key6", 6));
System.out.println("散列hash的所有鍵值對為:"+jedis.hgetAll("hash"));
System.out.println("将key6儲存的值加上一個整數,如果key6不存在則添加key6:"+jedis.hincrBy("hash", "key6", 3));
System.out.println("散列hash的所有鍵值對為:"+jedis.hgetAll("hash"));
System.out.println("删除一個或者多個鍵值對:"+jedis.hdel("hash", "key2"));
System.out.println("散列hash的所有鍵值對為:"+jedis.hgetAll("hash"));
System.out.println("散列hash中鍵值對的個數:"+jedis.hlen("hash"));
System.out.println("判斷hash中是否存在key2:"+jedis.hexists("hash","key2"));
System.out.println("判斷hash中是否存在key3:"+jedis.hexists("hash","key3"));
System.out.println("擷取hash中的值:"+jedis.hmget("hash","key3"));
System.out.println("擷取hash中的值:"+jedis.hmget("hash","key3","key4"));
}
/**
* 有序集合
*/
@Test
public void testSortedSet() {
Map<String,Double> map = new HashMap<String,Double>();
map.put("key2",1.2);
map.put("key3",4.0);
map.put("key4",5.0);
map.put("key5",0.2);
// 将一個或多個 member 元素及其 score 值加入到有序集 key 當中,如果某個 member 已經是有序集的成員,那麼更新這個 member 的 score 值
// score 值可以是整數值或雙精度浮點數
System.out.println(jedis.zadd("zset", 3,"key1"));
System.out.println(jedis.zadd("zset",map));
System.out.println("zset中的所有元素:"+jedis.zrange("zset", 0, -1));
System.out.println("zset中的所有元素:"+jedis.zrangeWithScores("zset", 0, -1));
System.out.println("zset中的所有元素:"+jedis.zrangeByScore("zset", 0,100));
System.out.println("zset中的所有元素:"+jedis.zrangeByScoreWithScores("zset", 0,100));
System.out.println("zset中key2的分值:"+jedis.zscore("zset", "key2"));
System.out.println("zset中key2的排名:"+jedis.zrank("zset", "key2"));
System.out.println("删除zset中的元素key3:"+jedis.zrem("zset", "key3"));
System.out.println("zset中的所有元素:"+jedis.zrange("zset", 0, -1));
System.out.println("zset中元素的個數:"+jedis.zcard("zset"));
System.out.println("zset中分值在1-4之間的元素的個數:"+jedis.zcount("zset", 1, 4));
System.out.println("key2的分值加上5:"+jedis.zincrby("zset", 5, "key2"));
System.out.println("key3的分值加上4:"+jedis.zincrby("zset", 4, "key3"));
System.out.println("zset中的所有元素:"+jedis.zrange("zset", 0, -1));
}
/**
* 排序
*/
@Test
public void testSort() {
jedis.lpush("collections", "ArrayList", "Vector", "Stack", "HashMap", "WeakHashMap", "LinkedHashMap");
System.out.println("collections的内容:"+jedis.lrange("collections", 0, -1));
SortingParams sortingParameters = new SortingParams();
// 當資料集中儲存的是字元串值時,你可以用 ALPHA,預設是升序
System.out.println("alpha排序方式:" + jedis.sort("collections",sortingParameters.alpha()));
System.out.println("===============================");
jedis.lpush("sortedList", "3","6","2","0","7","4");
System.out.println("sortedList排序前:"+jedis.lrange("sortedList", 0, -1));
System.out.println("升序:"+jedis.sort("sortedList", sortingParameters.asc()));
System.out.println("降序:"+jedis.sort("sortedList", sortingParameters.desc()));
System.out.println("===============================");
// 叢集下不支援分割表排序
/*jedis.lpush("userlist", "33");
jedis.lpush("userlist", "22");
jedis.lpush("userlist", "55");
jedis.lpush("userlist", "11");
jedis.hset("user:66", "name", "66");
jedis.hset("user:55", "name", "55");
jedis.hset("user:33", "name", "33");
jedis.hset("user:22", "name", "79");
jedis.hset("user:11", "name", "24");
jedis.hset("user:11", "add", "beijing");
jedis.hset("user:22", "add", "shanghai");
jedis.hset("user:33", "add", "guangzhou");
jedis.hset("user:55", "add", "chongqing");
jedis.hset("user:66", "add", "xi'an");
sortingParameters = new SortingParams();
// 符号 "->" 用于分割哈希表的鍵名(key name)和索引域(hash field),格式為 "key->field"
sortingParameters.get("user:*->name");
sortingParameters.get("user:*->add");
System.out.println(jedis.sort("userlist",sortingParameters));*/
}
}