1. 程式人生 > >* Redis(七):JedisCluster 操作API

* Redis(七):JedisCluster 操作API

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));*/
    }
}