`

2.Jedis对Redis数据的读取操作

阅读更多

1.Strings

 

package com.gqshao.redis.kv;

import com.gqshao.redis.JedisTest;
import org.junit.Test;

/**
 * Strings二进制数据
 */
public class StringsTest extends JedisTest {

    /**
     * set [key] [value] 设置一个key的value值
     * get [key] 根据key返回value
     * del [key] 删除
     */
    @Test
    public void testSet() {
        logger.info("set keys Tom : " + jedis.set("keys", "Tom"));
        logger.info("get keys : " + jedis.get("keys"));
        logger.info("del keys : " + jedis.del("keys"));
    }

    /**
     * setnx [key] [value] 当该key不存在时设置value,nx not exist
     */
    @Test
    public void testSetnx() {
        logger.info("set keysnx old : " + jedis.set("keysnx", "old"));
        logger.info("setnx keysnx ,key已存在,返回 0 : " + jedis.setnx("keysnx", "value"));
        logger.info("get keysnx :" + jedis.get("keysnx"));
        logger.info("del keysnx : " + jedis.del("keysnx"));
    }

    /**
     * setex [key] [seconds] [value] 设置key-value并设置过期时间,时间单位为秒
     */
    @Test
    public void testSetex() throws InterruptedException {
        logger.info("setex keysex 10 10sec : " + jedis.setex("keysex", 10, "10sec"));
        logger.info("get keysex : " + jedis.get("keysex"));
        logger.info("sleep 10 sec");
        Thread.sleep(10000);
        logger.info("get keysex : " + jedis.get("keysex"));
        logger.info("del keysex : " + jedis.del("keysex"));
    }

    /**
     * setrange [key] [offset] [value] 从指定的offset(从0开始计算)处开始,按照给定的value覆盖(index的值会被覆盖)
     */
    @Test
    public void testSetrange() {
        logger.info("set keyr1 \"Hello World\" : " + jedis.set("keyr1", "Hello World"));
        logger.info("setrange keyr1 6 Tom : " + jedis.setrange("keyr1", 6, "Tom"));
        logger.info("get keyr1 : " + jedis.get("keyr1"));
        logger.info("del keyr1 : " + jedis.del("keyr1"));
    }

    /**
     * mset [key1] [value1] [key2] [value2] ... 一次设置多个key,成功返回Ok
     */
    @Test
    public void testMset() {
        logger.info("mset keym1 value1 keym2 value2 keym3 value3 : " + jedis.mset("keym1", "value1", "keym2", "value2", "keym3", "value3"));
        logger.info("keys keym* : " + jedis.keys("keym*"));
        logger.info("get keym1 : " + jedis.get("keym1"));
        logger.info("del keym1 keym2 keym3 : " + jedis.del("keym1", "keym2", "keym3"));
        logger.info("keys keym* : " + jedis.keys("keym*"));
    }

    /**
     * msetnx [key1] [value1] [key2] [value2] ...
     * 一次设置多个key,只要有一个key已经存在,msetnx一个操作都不会执行
     */
    @Test
    public void testMsetnx() {
        logger.info("set keym1 old : " + jedis.set("keym1", "old"));
        logger.info("msetnx keym1 n1 keym2 n2 keym3 n3 keym4 n4 : " + jedis.msetnx("keym1", "n1", "keym2", "n2", "keym3", "n3", "keym4", "n4"));
        logger.info("keys keym* : " + jedis.keys("keym*"));
        logger.info("get keym1 : " + jedis.get("keym1"));
        logger.info("get keym4 : " + jedis.get("keym4"));
        logger.info("del keym1 : " + jedis.del("keym1"));
    }

    /**
     * getset [key] [value] 设置key的值,并返回key的旧值
     */
    @Test
    public void testGetset() {
        logger.info("set keygs value : " + jedis.set("keygs", "oldValue"));
        logger.info("getset keygs value : " + jedis.getSet("keygs", "newValue"));
        logger.info("get keygs : " + jedis.get("keygs"));
        logger.info("del keygs : " + jedis.del("keygs"));
    }

    /**
     * getrange [key] [startOffset] [endOffset]
     * 通过指定偏移量返回子字符串,左从0开始,右从-1开始 全闭集合
     */
    @Test
    public void testGetrange() {
        logger.info("set keyr 0123456789 : " + jedis.set("keyr", "0123456789"));
        logger.info("getrange keyr 0 5 : " + jedis.getrange("keyr", 0, 5));
        logger.info("getrange keyr 0 -1 :  " + jedis.getrange("keyr", 5, -1));
        logger.info("getrange keyr 0 -5 : " + jedis.getrange("keyr", 0, -5));
        logger.info("del keyr : " + jedis.del("keyr"));
    }

    /**
     * mget [key1] [key2] ...获取多个key的值List,key不存在返回null
     */
    @Test
    public void testMget() {
        logger.info("mset keym1 n1 keym3 n3  : " + jedis.mset("keym1", "n1", "keym3", "n3"));
        logger.info("mget keym1 keym2 keym3: " + jedis.mget("keym1", "keym2", "keym3"));
        logger.info("del keym1 keym3" + jedis.del("keym1", "keym3"));
    }

    /**
     * incr [key] value++,不是数字类型抛出异常,incr一个不存在的key,则value设置为1
     * incrby [key] [value] value-=[value],incrby一个不存在的key,则value设置为[value]
     * decr [key] value-- decr一个不存在的key,则value设置为1
     * decrby [key] [value] value-=[value],decrby一个不存在的key,则value设置为[value]
     */
    @Test
    public void testIncrDecr() {
        // incr
        logger.info("test incr");
        logger.info("incr keyi : " + jedis.incr("keyi"));
        logger.info("get keyi : " + jedis.get("keyi") + "\n");

        // value is not an integer
        logger.info("test value is not an integer");
        logger.info("set keyi a: " + jedis.set("keyi", "a"));
        try {
            logger.info("incr keyi : " + jedis.incr("keyi"));
        } catch (Exception e) {
            logger.warn("value不是数字类似抛出异常", e);
        }
        logger.info("del keyi : " + jedis.del("keyi") + "\n");

        logger.info("test incrby");
        logger.info("incrby keyint 10 : " + jedis.incrBy("keyint", 10) + "\n");

        logger.info("test decr");
        logger.info("decr keyint : " + jedis.decr("keyint") + "\n");

        logger.info("test decrby");
        logger.info("decrby keyint 10 : " + jedis.decrBy("keyint", 10));
        logger.info("decrby keyint2 10 : " + jedis.decrBy("keyint2", 10));
        logger.info("del keyint : " + jedis.del("keyint"));
        logger.info("del keyint2 : " + jedis.del("keyint2"));
    }

    /**
     * append [key] [value] 在原value后追加value,相当于value=value+"[value]",返回新Strings长度
     */
    @Test
    public void testAppend() {
        logger.info("set keye email : " + jedis.set("keye", "email"));
        logger.info("append keye @163.com : " + jedis.append("keye", "@163.com"));
        logger.info("get keye : " + jedis.get("keye"));
        logger.info("del keye : " + jedis.del("keye"));
    }

    /**
     * strlen [key] 取指定字符串长度 相当于length
     */
    @Test
    public void testStrlen() {
        logger.info("set keylen 0123456789 : " + jedis.set("keylen", "0123456789"));
        logger.info("strlen keylen : " + jedis.strlen("keylen"));
        logger.info("del keylen : " + jedis.del("keylen"));
    }
}

 

 

2.Lists

 

package com.gqshao.redis.kv;

import com.gqshao.redis.JedisTest;
import org.junit.Test;
import redis.clients.jedis.BinaryClient;

/**
 * Lists 是一个链表结构主要功能是push、pop等
 * Redis的List是双向链表,最大长度是2的32次方(4G)
 * index(下标) 正序(从左到右,从上到下)从0开始,逆序(从右到左,从下至上)从-1开始
 */
public class ListsTest extends JedisTest {

    /**
     * lpush [key] [value] 在key对应的list头部(左侧或上侧)添加Strings元素,返回Lists长度,可一次输入多个value,按输入顺序添加依次到头部
     * rpush [key] [value]  在key对应的list尾部(右侧或下侧)添加Strings元素,返回Lists长度,可一次输入多个value,按输入顺序添加到尾部
     * linsert [key] [index] [before|after] 在key对应的list指定value(value可能重复,在从头开始遇到的第一个生效)的前或后添加
     * lset [key] [index] [value] 通过指定下标修改value,注意下标不能超出已有范围
     * lrange [key] [start] [end] 返回指定下标范围内的元素(下标从0开始,尾部从-1开始)
     */
    @Test
    public void testPush() {
        // lpush
        logger.info("test lpush");
        logger.info("lpush mylist world : " + jedis.lpush("mylist", "world"));
        logger.info("lpush mylist hello : " + jedis.lpush("mylist", "hello"));
        logger.info("lrange mylist 0 -1 : " + jedis.lrange("mylist", 0, -1) + "\n");
        logger.info("lpush mylist a b c d : " + jedis.lpush("mylist", "a", "b", "c", "d"));
        logger.info("lrange mylist 0 -1 : " + jedis.lrange("mylist", 0, -1) + "\n");
        // rpush
        logger.info("test rpush");
        logger.info("rpush mylist 0 : " + jedis.rpush("mylist", "0"));
        logger.info("rpush mylist 1 2 3 4 : " + jedis.rpush("mylist", "1", "2", "3", "4"));
        logger.info("lrange mylist 0 -1 : " + jedis.lrange("mylist", 0, -1) + "\n");

        // linsert
        logger.info("test linsert");
        logger.info("linsert mylist 1 after 1 : " + jedis.linsert("mylist", BinaryClient.LIST_POSITION.AFTER, "1", "1"));
        logger.info("linsert mylist 3 before 3 : " + jedis.linsert("mylist", BinaryClient.LIST_POSITION.BEFORE, "3", "3"));
        logger.info("linsert mylist 1 after after_1 : " + jedis.linsert("mylist", BinaryClient.LIST_POSITION.AFTER, "1", "after_1"));
        logger.info("linsert mylist 3 before before_3 : " + jedis.linsert("mylist", BinaryClient.LIST_POSITION.BEFORE, "3", "before_3"));
        logger.info("linsert mylist 3 after after_3 : " + jedis.linsert("mylist", BinaryClient.LIST_POSITION.AFTER, "3", "after_3"));
        logger.info("lrange mylist 0 -1 : " + jedis.lrange("mylist", 0, -1) + "\n");

        // del
        logger.info("del mylist : " + jedis.del("mylist") + "\n");

        // lset
        logger.info("test lset");
        logger.info("lpush mylist a b c d : " + jedis.lpush("mylist", "a", "b", "c", "d"));
        logger.info("lrange mylist 0 -1 : " + jedis.lrange("mylist", 0, -1) + "\n");
        logger.info("lset mylist 0 zero : " + jedis.lset("mylist", 0, "zero"));
        logger.info("lset mylist -2 three : " + jedis.lset("mylist", -2, "three"));
        try {
            logger.info("lset mylist 4 four : " + jedis.lset("mylist", 4, "four"));
        } catch (Exception e) {
            logger.warn("lset修改值不能超过Lists目前长度", e);
        }
        logger.info("lrange mylist 0 -1 : " + jedis.lrange("mylist", 0, -1) + "\n");

        // del
        logger.info("del mylist : " + jedis.del("mylist") + "\n");
    }

    /**
     * lrem [key] [count] [value] 从key所对应的Lists中删除count个指定value
     * count>0时,从头到尾删除count个value
     * count<0时,从尾到头删除count个value
     * count=0时,全部删除
     */
    @Test
    public void testLrem() {
        // count>0
        logger.info("rpush mylist foo foo bar foo foo : " + jedis.rpush("mylist", "foo", "foo", "bar", "foo", "foo"));
        logger.info("lrange mylist 0 -1 : " + jedis.lrange("mylist", 0, -1) + "\n");
        logger.info("lrem mylist 2 foo : " + jedis.lrem("mylist", 2, "foo"));
        logger.info("lrange mylist 0 -1 : " + jedis.lrange("mylist", 0, -1) + "\n");

        // count<0
        logger.info("lrem mylist -1 foo : " + jedis.lrem("mylist", -1, "foo"));
        logger.info("lrange mylist 0 -1 : " + jedis.lrange("mylist", 0, -1));
        // del
        logger.info("del mylist : " + jedis.del("mylist") + "\n");

        // count=0
        logger.info("rpush mylist foo foo bar foo foo : " + jedis.rpush("mylist", "foo", "foo", "bar", "foo", "foo"));
        logger.info("lrem mylist 0 foo : " + jedis.lrem("mylist", 0, "foo"));
        logger.info("lrange mylist 0 -1 : " + jedis.lrange("mylist", 0, -1) + "\n");
        // del
        logger.info("del mylist : " + jedis.del("mylist") + "\n");
    }

    /**
     * ltrim [key] [start] [end] 保留list中指定范围内的value(头从0开始,尾从-1开始)
     * 如果start在end之后,相当于清空Lists
     */
    @Test
    public void testLtrim() {
        logger.info("rpush mylist 0 1 2 3 4 : " + jedis.rpush("mylist", "0", "1", "2", "3", "4"));
        logger.info("lrange mylist 0 -1 : " + jedis.lrange("mylist", 0, -1) + "\n");

        logger.info("保留最大范围,没有数据被移除");
        logger.info("ltrim mylist 0 -1 : " + jedis.ltrim("mylist", 0, -1));
        logger.info("lrange mylist 0 -1 : " + jedis.lrange("mylist", 0, -1) + "\n");

        logger.info("保留1到-2,头尾各删除一个");
        logger.info("ltrim mylist 1 -2 : " + jedis.ltrim("mylist", 1, -2));
        logger.info("lrange mylist 0 -1 : " + jedis.lrange("mylist", 0, -1) + "\n");

        logger.info("保留1到1,保留的结果等于 lindex mylist 1 取到的值");
        logger.info("lindex mylist 1 : " + jedis.lindex("mylist", 1));
        logger.info("ltrim mylist 1 1 : " + jedis.ltrim("mylist", 1, 1));
        logger.info("lrange mylist 0 -1 : " + jedis.lrange("mylist", 0, -1) + "\n");
        logger.info("del mylist : " + jedis.del("mylist") + "\n");

        // start > end
        logger.info("如果start在end之后,相当于全删");
        logger.info("rpush mylist 0 1 2 3 4 : " + jedis.rpush("mylist", "0", "1", "2", "3", "4"));
        logger.info("ltrim mylist 1 0 : " + jedis.ltrim("mylist", 1, 0));
        logger.info("lrange mylist 0 -1 : " + jedis.lrange("mylist", 0, -1) + "\n");

        // del
        logger.info("del mylist : " + jedis.del("mylist") + "\n");
    }

    /**
     * lpop [key] 从list头部移出并返回一个元素
     * rpop [key] 从list尾部移出并返回一个元素
     * rpoplpush [list1] [list2] 从第一个list1尾部移出一个元素,添加到list2头部,并返回该元素,rpoplpush是一个原子操作
     */
    @Test
    public void testPop() {

        logger.info("rpush mylist 0 1 2 3 4 : " + jedis.rpush("mylist", "0", "1", "2", "3", "4") + "\n");

        // lpop
        logger.info("test lpop");
        logger.info("lpop mylist : " + jedis.lpop("mylist") + "\n");

        // rpop
        logger.info("test rpop");
        logger.info("rpop mylist : " + jedis.rpop("mylist"));
        logger.info("del mylist : " + jedis.del("mylist") + "\n");


        // rpoplpush
        logger.info("test rpoplpush");
        logger.info("rpush mylist1 0 1 2 3 4 : " + jedis.rpush("mylist1", "0", "1", "2", "3", "4"));
        logger.info("rpush mylist2 zero one two : " + jedis.rpush("mylist2", "zero", "one", "two"));
        logger.info("rpoplpush mylist1 mylist2 : " + jedis.rpoplpush("mylist1", "mylist2"));
        logger.info("lrange mylist1 0 -1 : " + jedis.lrange("mylist1", 0, -1));
        logger.info("lrange mylist2 0 -1 : " + jedis.lrange("mylist2", 0, -1));
        logger.info("del mylist1 mylist2: " + jedis.del("mylist1", "mylist2"));

    }

    /**
     * lindex [key] [index] 返回Lists指定下标的value
     * llen [key] 返回Lists的长度
     */
    @Test
    public void testLindexAndLlen() {
        // lindex
        logger.info("lindex");
        logger.info("rpush mylist 0 1 2 3 4 : " + jedis.rpush("mylist", "0", "1", "2", "3", "4"));
        logger.info("lindex mylist 3 : " + jedis.lindex("mylist", 3));
        logger.info("lindex mylist -3 : " + jedis.lindex("mylist", -3) + "\n");

        // llen
        logger.info("test llen");
        logger.info("llen mylist : " + jedis.llen("mylist"));

        // del
        logger.info("del mylist : " + jedis.del("mylist"));
    }
}

 

3.HashesTest

package com.gqshao.redis.kv;

import com.google.common.collect.Maps;
import com.gqshao.redis.JedisTest;
import org.junit.Test;

import java.util.Map;

/**
 * Hashes Strings类型的field和value的映射表.它的添加、删除操作都是O(1)(平均)。hash特别适合用于存储对象
 * 对于Hashes key是名称、field是hashmap的key,value是hashmap的value
 */
public class HashesTest extends JedisTest {
    /**
     * hset [key] [field] [value] 设置field的value
     * hsetnx [key] [field] [value] 设置field的value,如果key不存在,则先创建,如果field已经存在返回0,nx是not exist
     * hmset [key] [field1] [value2] [field2] [value3]  同时设置hash的多个field
     */
    @Test
    public void testSet() {
        // hset
        logger.info("hset myhash field1 hello : " + jedis.hset("myhash", "field1", "hello"));
        logger.info("hget myhash field1 : " + jedis.hget("myhash", "field1") + "\n");

        // hsetnx
        logger.info("hget myhash field1 : " + jedis.hget("myhash", "field1"));
        logger.info("hsetnx myhash field1 new : " + jedis.hsetnx("myhash", "field1", "new"));
        logger.info("hget myhash field1 : " + jedis.hget("myhash", "field1"));
        logger.info("hget myhash field2 : " + jedis.hget("myhash", "field2"));
        logger.info("hsetnx myhash field2 world : " + jedis.hsetnx("myhash", "field2", "world"));
        logger.info("hget myhash field2 : " + jedis.hget("myhash", "field2") + "\n");

        // hmset
        logger.info("test hmset");
        Map<String, String> kvs = Maps.newHashMap();
        kvs.put("field1", "newvalue");
        kvs.put("field3", "value3");
        logger.info("hmset myhash field1 newvalue field3 value3", jedis.hmset("myhash", kvs));
        logger.info("hget myhash field1 : " + jedis.hget("myhash", "field1"));
        logger.info("hget myhash field3 : " + jedis.hget("myhash", "field3") + "\n");

        // del
        logger.info("del myhash : " + jedis.del("myhash"));
    }

    /**
     * hget [key] [field] 获取指定key,field的value
     * hmget [key] [fields...] 获取全部指定key,field的value的List集合
     * hincrby [key] [field] [value] 通过指定field,给value加上给定的long值,value必须是Integer类型,不可以是浮点数或字符
     * hincrbyfloat [key] [field] [value] 通过指定field,给value加上给定的float值,value必须是数字类型
     */
    @Test
    public void testGet() {
        // hget
        logger.info("test hget");
        logger.info("hset myhash field1 hello : " + jedis.hset("myhash", "field1", "hello"));
        logger.info("hget myhash field1 : " + jedis.hget("myhash", "field1") + "\n");

        // hmget
        logger.info("test hmget");
        logger.info("hset myhash field2 world : " + jedis.hset("myhash", "field2", "world"));
        logger.info("hmget myhash field1 field2 : " + jedis.hmget("myhash", "field1", "field2") + "\n");

        // hincrby
        logger.info("test hincrby");
        logger.info("hset myhash field3 5 : " + jedis.hset("myhash", "field3", "5"));
        logger.info("hget myhash field3 : " + jedis.hget("myhash", "field3"));
        try {
            logger.info("hincrby myhash field1 1 : " + jedis.hincrBy("myhash", "field1", 1));
        } catch (Exception e) {
            logger.warn("hincrby 必须作用于integer类型", e);
        }
        logger.info("hincrby myhash field3 10 : " + jedis.hincrBy("myhash", "field3", 10));
        logger.info("hget myhash field3 : " + jedis.hget("myhash", "field3"));
        logger.info("hincrby myhash field3 -20 : " + jedis.hincrBy("myhash", "field3", -20));
        logger.info("hget myhash field3 : " + jedis.hget("myhash", "field3") + "\n");

        // hincrbyfloat
        logger.info("test hincybyfloat");
        logger.info("hincrbyfloat myhash field3 0.25 : " + jedis.hincrByFloat("myhash", "field3", 0.25));
        logger.info("hget myhash field3 : " + jedis.hget("myhash", "field3"));

        // del
        logger.info("del myhash : " + jedis.del("myhash"));
    }

    /**
     * hexists [key] [field] 测试指定field是否存在 返回值boolean
     * hlen [key] 返回指定hash的field数量,相当于size
     * hdel [key] [field] 删除指定key和field的value,相当于remove
     * hkeys [key] 返回指定key的hash所有field的Set集合
     * hvals [key] 返回指定key的hash所有value的List集合
     * hgetall [key] 返回全部数据,返回值为Map<K,V>
     */
    @Test
    public void testFieldAndValue() {
        // hexists
        logger.info("test hexists");
        logger.info("hexists myhash field1 : " + jedis.hexists("myhash", "field1"));
        logger.info("hset myhash field1 hello : " + jedis.hset("myhash", "field1", "hello"));
        logger.info("hexists myhash field1 : " + jedis.hexists("myhash", "field1") + "\n");

        // hlen
        logger.info("test hlen");
        logger.info("hset myhash field2 world : " + jedis.hset("myhash", "field2", "world"));
        logger.info("hset myhash field3 !! : " + jedis.hset("myhash", "field3", "!!"));
        logger.info("hlen myhash : " + jedis.hlen("myhash") + "\n");

        // hdel
        logger.info("hdel myhash field3 : " + jedis.hdel("myhash", "field3") + "\n");

        // hkeys
        logger.info("hkeys myhash : " + jedis.hkeys("myhash") + "\n");

        // hvals
        logger.info("hvals myhash : " + jedis.hvals("myhash") + "\n");

        // hgetall
        logger.info("hgetall myhash : " + jedis.hgetAll("myhash") + "\n");

        // del
        logger.info("del myhash : " + jedis.del("myhash") + "\n");
    }
}

/**
 * hscan 扫描
 * @see  http://redis.io/commands/scan
 * hscan key 0 MATCH *11* COUNT 1000
 * 有scan对应String sscan对应Sets hscan对应Hashes zscan对应Sorted Sets
 * Lists有lrange返回指定下标的元素
 */
@Test
public void testHscan() {
    long[] value = new long[]{1L, 3L, 5L, 7L};
    Jedis jedis = null;
    String key = "key";

    try {
        jedis = pool.getResource();
        jedis.del(key);
        Pipeline pipeline = jedis.pipelined();

        for (int i = 0; i < 10000; i++) {
            pipeline.hincrBy(key, "value_" + i, value[((int) (Math.random() * 4))]);
        }
        List<Object> results = pipeline.syncAndReturnAll();
        logger.info("写入长度 {}", results.size());
    } catch (Exception e) {
        logger.error("写入异常", e);
    } finally {
        if (null != jedis) {
            jedis.close();
        }
    }

    // 游标初始值为0
    String cursor = "0";
    int i = 0;
    Set<String> values = Sets.newHashSet();
    ScanParams scanParams = new ScanParams();
    scanParams.match("value_*");
    scanParams.count(1000);
    try {
        jedis = pool.getResource();
        do {
            ScanResult<Map.Entry<String, String>> hscan = jedis.hscan(key, cursor, scanParams);
            cursor = hscan.getStringCursor();
            List<Map.Entry<String, String>> result = hscan.getResult();
            if (CollectionUtils.isEmpty(result)) {
                logger.error("本次迭代数量为0");
                continue;
            } else {
                logger.info("本次迭代数量为{}", result.size());
            }
            for (Map.Entry<String, String> entry : result) {
                values.add(entry.getKey());
                i++;
            }
        } while (!"0".equals(cursor));
        logger.info("值个数 {}", values.size());
        logger.info("i 长度 {}", i);
    } catch (Exception e) {
        logger.error("读取异常", e);
    } finally {
        if (null != jedis) {
            jedis.close();
        }
    }
}

 

4.Sets

 

package com.gqshao.redis.kv;

import com.gqshao.redis.JedisTest;
import org.junit.Test;

/**
 * Sets 是无序集合 Sets中的value被称为member(成员)
 */
public class SetsTest extends JedisTest {

    /**
     * sadd [key] [members...] 添加一个或多个value members
     * smembers [key] 返回value members组装成Set集合
     * srem [key] [members...]指定value删除Sets中一个或多个values members并返回影响数
     * spop [key] 随机删除并返回一个元素
     * srandmember [key] 随机返回一个元素,但不删除
     */
    @Test
    public void testAddAndDel() {
        // myset
        logger.info("test sadd");
        logger.info("sadd myset a b c d : " + jedis.sadd("myset", "a", "b", "c", "d"));
        logger.info("smembers myset : " + jedis.smembers("myset") + "\n");

        // srem
        logger.info("test srem");
        logger.info("srem myset a b : " + jedis.srem("myset", "a", "b"));
        logger.info("srem myset a c : " + jedis.srem("myset", "a", "c"));
        logger.info("smembers myset : " + jedis.smembers("myset"));
        logger.info("del myset : " + jedis.del("myset") + "\n");


        // spop
        logger.info("test spop");
        logger.info("sadd myset a b c d : " + jedis.sadd("myset", "a", "b", "c", "d"));
        logger.info("spop myset : " + jedis.spop("myset"));
        logger.info("spop myset : " + jedis.spop("myset"));
        logger.info("smembers myset : " + jedis.smembers("myset"));
        logger.info("del myset : " + jedis.del("myset") + "\n");

        // srandmember
        logger.info("test srandmember");
        logger.info("sadd myset a b c d : " + jedis.sadd("myset", "a", "b", "c", "d"));
        logger.info("srandmember myset : " + jedis.srandmember("myset"));
        logger.info("srandmember myset : " + jedis.srandmember("myset"));
        logger.info("smembers myset : " + jedis.smembers("myset"));
        logger.info("del myset : " + jedis.del("myset") + "\n");
    }

    /**
     * sdiff [key1] [key...] 输出集合1 与 其他(一个或多个)集合value的差集
     * sdiffstore [dstkey] [key1] [key...] 将sdiff的差集结果保存到一个新的结合中
     *
     * sinter [key...] 输出所有集合的交集
     * sinterstore [dstkey] [key...] 将sinter的交集结果保存到一个新的结合中
     *
     * sunion  [key...] 输出所有集合的并集
     * sunionstore [dstkey] [key...] 将sunion的并集结果保存到一个新的结合中
     */
    @Test
    public void testSet() {
        logger.info("sadd myset1 1 2 3 foo bar : " + jedis.sadd("myset1", "1", "2", "3", "foo", "bar"));
        logger.info("sadd myset2 a b c foo bar : " + jedis.sadd("myset2", "a", "b", "c", "foo", "bar"));
        logger.info("sadd myset3 1 2 a : " + jedis.sadd("myset3", "1", "2", "a"));

        // sdiff sdiffstore
        logger.info("test sdiff sdiffstore");
        logger.info("sdiff myset1 myset2 myset3 : " + jedis.sdiff("myset1", "myset2", "myset3"));
        logger.info("sdiff myset2 myset1 myset3 : " + jedis.sdiff("myset2", "myset1", "myset3"));

        logger.info("sdiffstore resultset myset1 myset3 : " + jedis.sdiffstore("resultset", "myset1", "myset3"));
        logger.info("smembers resultset : " + jedis.smembers("resultset"));
        logger.info("del resultset : " + jedis.del("resultset") + "\n");

        // sinter sinterstore
        logger.info("test sinter sinterstore");
        logger.info("sinter myset1 myset2" + jedis.sinter("myset1", "myset2"));
        logger.info("sinterstore resultset myset2 myset3 : " + jedis.sinterstore("resultset", "myset2", "myset3"));
        logger.info("smembers resultset : " + jedis.smembers("resultset"));
        logger.info("del resultset : " + jedis.del("resultset") + "\n");

        // sunion sunionstore
        logger.info("test sunion sunionstore");
        logger.info("sunion myset1 myset2" + jedis.sunion("myset1", "myset2"));
        logger.info("sunionstore resultset myset2 myset3 : " + jedis.sunionstore("resultset", "myset2", "myset3"));
        logger.info("smembers resultset : " + jedis.smembers("resultset"));
        logger.info("del resultset : " + jedis.del("resultset") + "\n");


        logger.info("del myset1 : " + jedis.del("myset1"));
        logger.info("del myset2 : " + jedis.del("myset2"));
        logger.info("del myset3 : " + jedis.del("myset3"));
    }

    /**
     * smove [srckey] [dstkey] [member] 将指定的member从集合srckey移动到集合dstkey中
     */
    @Test
    public void testSmove() {
        logger.info("sadd myset1 1 2 3 foo bar : " + jedis.sadd("myset1", "1", "2", "3", "foo", "bar"));
        logger.info("sadd myset2 a b c foo bar : " + jedis.sadd("myset2", "a", "b", "c", "foo", "bar"));
        logger.info("smove myset1 myset2 1 : " + jedis.smove("myset1", "myset2", "1"));
        logger.info("smove myset1 myset2 3 : " + jedis.smove("myset1", "myset2", "3"));
        logger.info("smembers myset1 : " + jedis.smembers("myset1"));
        logger.info("smembers myset2 : " + jedis.smembers("myset2"));
        logger.info("del myset1 : " + jedis.del("myset1"));
        logger.info("del myset2 : " + jedis.del("myset2"));
    }

    /**
     * smembers [key] 返回集合所有members(返回值Set)
     * scard [key] 返回集合元素个数,相当于size
     * sismember [key] [member] 测试元素是否在集合中,返回boolean,相当于contains
     */
    @Test
    public void testMember() {
        logger.info("sadd myset1 1 2 bar : " + jedis.sadd("myset1", "1", "2", "bar"));
        logger.info("sadd myset2 a b c foo bar : " + jedis.sadd("myset2", "a", "b", "c", "foo", "bar") + "\n");

        logger.info("test smembers");
        logger.info("smembers myset1 : " + jedis.smembers("myset1"));
        logger.info("smembers myset2 : " + jedis.smembers("myset2") + "\n");

        logger.info("test scard");
        logger.info("scard myset1 : " + jedis.scard("myset1"));
        logger.info("scard myset2 : " + jedis.scard("myset2") + "\n");

        logger.info("test sismember");
        logger.info("sismember : " + jedis.sismember("myset1", "1"));
        logger.info("sismember : " + jedis.sismember("myset1", "foo"));


        logger.info("del myset1 : " + jedis.del("myset1"));
        logger.info("del myset2 : " + jedis.del("myset2"));

    }


}

 

 5.SortedSets

 

package com.gqshao.redis.kv;

import com.google.common.collect.Maps;
import com.gqshao.redis.JedisTest;
import org.junit.Test;
import redis.clients.jedis.Tuple;

import java.util.Map;
import java.util.Set;

/**
 * Sorted Sets是Sets的升级版本,由score(优先级)和value组成,即集合中每个元素都关联一个double类型的score
 * Sorted Sets是List和Hashes的混合体,Sorted Sets最经常的使用方式是作为索引来使用,把要排序的字段作为按score存储,元素的id作为value
 * Rank与Lists中index(下标),功能一致,正序(从左到右,从上到下)从0开始,逆序(从右到左,从下至上)从-1开始
 * 可以有相同的score值
 */
public class SortedSetsTest extends JedisTest {

    /**
     * 添加操作
     * <p/>
     * zadd [key] [score] [member] 向集合中添加元素,score可以任意指定负数、零、正数,如果member则更新score
     * zrem [key] [member...] 删除集合中元素,可同时删除多个
     * zincrby [key] [increment] [member] 如果member存在,score+=increment,如果member不存在则添加member,score=increment
     */
    @Test
    public void testZadd() {
        logger.info("test zadd");
        logger.info("zadd myzset 0 zero : " + jedis.zadd("myzset", 0, "zero"));
        Map<String, Double> memberScore = Maps.newHashMap();
        memberScore.put("foo", -1.0);
        memberScore.put("bar", -1.5);
        memberScore.put("one", 1d);
        logger.info("zadd myzset -1 foo -1.5 bar 1 one: " + jedis.zadd("myzset", memberScore));

        logger.info("zrange myzset 0 -1 withscores : ");
        Set<Tuple> myzset = jedis.zrangeWithScores("myzset", 0, -1);
        for (Tuple tuple : myzset) {
            logger.info(tuple.getScore() + " : " + tuple.getElement());
        }
        logger.info("\n");
        logger.info("test zadd 更新foo的score");
        logger.info("zadd myzset 10 foo : " + jedis.zadd("myzset", 10, "foo"));
        logger.info("zrange myzset 0 -1 withscores : ");
        myzset = jedis.zrangeWithScores("myzset", 0, -1);
        for (Tuple tuple : myzset) {
            logger.info(tuple.getScore() + " : " + tuple.getElement());
        }

        logger.info("\n");
        logger.info("test zrem");
        logger.info("zrem myzset bar foo: " + jedis.zrem("myzset", "bar", "foo"));
        logger.info("zrange myzset 0 -1 withscores : ");
        myzset = jedis.zrangeWithScores("myzset", 0, -1);
        for (Tuple tuple : myzset) {
            logger.info(tuple.getScore() + " : " + tuple.getElement());
        }
        logger.info("\n");
        logger.info("test zincrby");
        logger.info("zincrby myzset -1 one: " + jedis.zincrby("myzset", -1, "one"));
        logger.info("zincrby myzset 1.5 foo: " + jedis.zincrby("myzset", 1.5, "foo"));
        logger.info("zrange myzset 0 -1 withscores : ");
        myzset = jedis.zrangeWithScores("myzset", 0, -1);
        for (Tuple tuple : myzset) {
            logger.info(tuple.getScore() + " : " + tuple.getElement());
        }

        logger.info("del myzset : " + jedis.del("myzset"));
    }

    /**
     * 查询操作
     * <p/>
     * 通过下标
     * zrange [key] [start] [end] 从正向指定member下标返回集合元素(返回值Set<String),可以在最后输入withscores(返回值为Set<Tuple>)
     * zrevrange [key] [start] [end] 从逆向(从右向左)指定member下标返回集合元素(返回值Set<String),可以在最后输入withscores(返回值为Set<Tuple>)
     * <p/>
     * 通过顺序
     * zrank [key] [member] 返回member的正序排序数,相当于正序下标
     * zrevrank [key] [member] 返回member的逆向排序数,不同于逆序下标,仍是从0、1、2这样的数
     * <p/>
     * 通过score(优先级)
     * zrangebyscore [key] [min] [max] [withscores] [limit offset count] 指定集合score的最小值和最大值,返回member
     * <p/>
     * score顺序+字典范围
     *
     * zrangebylex [key] [min] [max] 按照score顺序,判断member是否在给定字符区间,遇到第一个不符合的情况后返回之前找到的结果
     * min可以用"-"代替,表示从开始,"("开区间,"["闭区间,比如想要包含zero可以用[zero或比ze顺序大的(zh
     * 顺序比较 负数<0<正数,数字<字母, 字母顺序按字母表排序
     * 如果想只通过字典范围判断,需要把score设为相同值(比如都为0)
     */
    @Test
    public void testRank() {
        Map<String, Double> memberScore = Maps.newHashMap();
        memberScore.put("minus two", -2d);
        memberScore.put("minus one", -1d);
        memberScore.put("zero", 0.0);
        memberScore.put("one", 1.0);
        memberScore.put("two", 2.0);
        logger.info("zadd myzset -2 \"minus two\" -1 \"minus one\" 0 zero 1 one 2 two : "
                + jedis.zadd("myzset", memberScore) + "\n");

        // zrange
        logger.info("zrange myzset 0 -1 withscores : ");
        Set<Tuple> myzset = jedis.zrangeWithScores("myzset", 0, -1);
        for (Tuple tuple : myzset) {
            logger.info(tuple.getScore() + " : " + tuple.getElement());
        }

        // zrevrange
        logger.info("\n");
        logger.info("zrevrange myzset 0 -1 withscores : ");
        myzset = jedis.zrevrangeWithScores("myzset", 0, -1);
        for (Tuple tuple : myzset) {
            logger.info(tuple.getScore() + " : " + tuple.getElement());
        }
        logger.info("zrevrange myzset 0 3 withscores : ");
        myzset = jedis.zrevrangeWithScores("myzset", 0, 3);
        for (Tuple tuple : myzset) {
            logger.info(tuple.getScore() + " : " + tuple.getElement());
        }

        // zrank
        logger.info("\n");
        logger.info("test zrank");
        logger.info("zrank myzset \"minus two\" : " + jedis.zrank("myzset", "minus two"));
        logger.info("zrank myzset zero : " + jedis.zrank("myzset", "zero"));

        // zrevrank
        logger.info("\n");
        logger.info("test zrevrank");
        logger.info("zrevrank myzset \"minus two\" : " + jedis.zrevrank("myzset", "minus two"));
        logger.info("zrevrank myzset zero : " + jedis.zrevrank("myzset", "zero"));
        logger.info("zrevrank myzset two : " + jedis.zrevrank("myzset", "two"));

        // zrangebyscore
        logger.info("\n");
        logger.info("test zrangebyscore");
        logger.info("zrangebyscore myzset -1 1 withscores : ");
        myzset = jedis.zrangeByScoreWithScores("myzset", -1, 1);
        for (Tuple tuple : myzset) {
            logger.info(tuple.getScore() + " : " + tuple.getElement());
        }

        // zrangebylex

        logger.info("\n");
        logger.info("test zrangebylex");
        memberScore = Maps.newHashMap();
        memberScore.put("-10", -10.0);
        memberScore.put("10", 10.0);
        logger.info("zadd myzset -10 -10 10 10 : "
                + jedis.zadd("myzset", memberScore) + "\n");
        logger.info("zrangebylex myzset (-10 (z : ");
        Set<String> bylexRex = jedis.zrangeByLex("myzset", "(-10", "(z");
        for (String res : bylexRex) {
            logger.info(res);
        }
        logger.info("10、one、two虽然在给定(10 (z区间中,但由于score比zero大,查询在遇到zero后不满足条件就返回了");
        logger.info("zrangebylex myzset [-10 (zh : ");
        bylexRex = jedis.zrangeByLex("myzset", "[-10", "(zh");
        for (String res : bylexRex) {
            logger.info(res);
        }

        logger.info("del myzset : " + jedis.del("myzset"));
    }

    /**
     * zrangebyscore [key] [min] [max] 指定集合score的最小值和最大值,返回member
     * zcount [key] [min] [max] 指定集合score的最小值和最大值,统计member数量
     * zcard [key] 统计集合中member个数
     * zscore [key] [member] 返回member的score
     */
    @Test
    public void testScore() {
        Map<String, Double> memberScore = Maps.newHashMap();
        memberScore.put("minus two", -2d);
        memberScore.put("minus one", -1d);
        memberScore.put("zero", 0.0);
        memberScore.put("one", 1.0);
        memberScore.put("two", 2.0);
        logger.info("zadd myzset -2 \"minus two\" -1 \"minus one\" 0 zero 1 one 2 two : "
                + jedis.zadd("myzset", memberScore) + "\n");

        // zrangebyscore
        logger.info("zrangebyscore myzset -1 1 withscores : ");
        Set<Tuple> myzset = jedis.zrangeByScoreWithScores("myzset", -1, 1);
        for (Tuple tuple : myzset) {
            logger.info(tuple.getScore() + " : " + tuple.getElement());
        }

        // zcount
        logger.info("\n");
        logger.info("zcount");
        logger.info("zcount myzset -1 1 withscores : " + jedis.zcount("myzset", -1, 1) + "\n");

        // zcard
        logger.info("zcard");
        logger.info("zcard myzset : " + jedis.zcard("myzset") + "\n");

        logger.info("zscore");
        logger.info("zscore myzset one: " + jedis.zscore("myzset", "one") + "\n");


        logger.info("del myzset : " + jedis.del("myzset"));

    }

    /**
     * zrem [key] [member...] 删除集合中元素,可同时删除多个
     * zremrangebyrank [key] [start] [end] 根据下标删除元素
     * zremrangebysocre [key] [start] [end] 根据给定score区间删除元素
     */
    @Test
    public void testRem() {
        Map<String, Double> memberScore = Maps.newHashMap();
        memberScore.put("minus two", -2d);
        memberScore.put("minus one", -1d);
        memberScore.put("zero", 0.0);
        memberScore.put("one", 1.0);
        memberScore.put("two", 2.0);
        memberScore.put("three", 3.0);
        logger.info("zadd myzset -2 \"minus two\" -1 \"minus one\" 0 zero 1 one 2 two 3 three : "
                + jedis.zadd("myzset", memberScore));
        logger.info("zrange myzset 0 -1 withscores : ");
        Set<Tuple> myzset = jedis.zrangeWithScores("myzset", 0, -1);
        for (Tuple tuple : myzset) {
            logger.info(tuple.getScore() + " : " + tuple.getElement());
        }


        // zremrangebyrank
        logger.info("\n");
        logger.info("test zremrangebyrank");
        logger.info("zremrangebyrank myzset 0 2 : " + jedis.zremrangeByRank("myzset", 0, 2));
        logger.info("zrange myzset 0 -1 withscores : ");
        myzset = jedis.zrangeWithScores("myzset", 0, -1);
        for (Tuple tuple : myzset) {
            logger.info(tuple.getScore() + " : " + tuple.getElement());
        }

        // 重建myzset
        logger.info("del myzset : " + jedis.del("myzset"));
        logger.info("zadd myzset -2 \"minus two\" -1 \"minus one\" 0 zero 1 one 2 two 3 three : "
                + jedis.zadd("myzset", memberScore) + "\n");

        // zremrangebyscore
        logger.info("test zremrangebyscore");
        logger.info("zremrangebyscore myzset 0 2 : " + jedis.zremrangeByScore("myzset", 0, 2));
        logger.info("zrange myzset 0 -1 withscores : ");
        myzset = jedis.zrangeWithScores("myzset", 0, -1);
        for (Tuple tuple : myzset) {
            logger.info(tuple.getScore() + " : " + tuple.getElement());
        }

        // del
        logger.info("del myzset : " + jedis.del("myzset"));
    }
}

 

 

 

1
0
分享到:
评论

相关推荐

    jedis操作Redis

    通过Jedis,开发者可以轻松地在Java应用中实现对Redis的各种操作,如设置和获取键值、执行命令、订阅发布等。 **安装Redis** 1. 下载Redis官方发行版:访问Redis官网(http://redis.io/download)下载适合操作系统...

    redis辅助文档 + jedis

    以下是对Redis和Jedis的详细知识点介绍: **1. Redis基础知识** - **数据类型**: Redis支持五大数据类型:字符串(Strings)、哈希(Hashes)、列表(Lists)、集合(Sets)和有序集合(Sorted Sets)。 - **持久化**: ...

    Java中利用jedis操作redis示例.zip

    总结,Java通过Jedis库操作Redis提供了丰富且高效的接口,涵盖基本的数据操作、集合类型操作、事务处理、发布订阅以及连接池管理等多个方面。通过掌握这些知识点,开发者可以轻松地将Redis集成到Java项目中,实现...

    使用java时间连接池连接redis,单例模式和集群模式.docx

    在 Redis 集群中,每个节点既可以作为主节点也可以作为从节点,主节点负责写入数据,而从节点负责读取数据。 Java Redis 客户端 Java Redis 客户端是 Java 应用程序连接 Redis 服务器的桥梁。通过使用 Java Redis ...

    关于Jedis连接Linux上的redis出现 DENIED Redis is running in protected mode问题的解决方案

    ### 关于Jedis连接Linux上的Redis出现DENIED Redis is running in protected mode问题的解决方案 #### 一、问题背景 在尝试使用Jedis客户端通过网络连接Linux服务器上的Redis时,可能会遇到一个常见的错误提示:...

    java redis使用之利用jedis实现redis消息队列.docx

    它提供了丰富的 API 来操作 Redis 中的各种数据结构,如字符串、列表、集合等,并且支持多种数据类型的操作,包括但不限于发布/订阅模式、事务处理等。 #### 三、项目环境配置 在开始编码之前,我们需要搭建好开发...

    jedis2.x使用指南.pdf

    Jedis是一个广泛使用的Redis的Java客户端,它提供了对Redis操作的全面支持,并通过一些高级特性来增强操作的性能和功能。本文将详细讲解Jedis的多个关键特性,包括其对Redis支持的全貌、如何通过Jedis实现Redis的...

    Redis-x64-5.0.9.zip

    可以使用各种语言的Redis客户端连接,如Python的`redis-py`,Java的`Jedis`等。 13. **安全策略**: Redis可以通过设置密码认证,限制只允许特定IP连接,增加安全性。 14. **监控与性能分析**: Redis提供了`...

    java大数据案例_8Redis、Thrift、Hadoop2

    2. **数据操作:** - 使用`lpop`和`rpop`弹出队首和队尾元素:`redis&gt;lpopstudent`...`redis&gt;rpopstudent` - 使用`lrem`删除指定元素:`redis&gt;lremstudenta3` - 使用`keys*`命令查看所有key:`redis&gt;keys*` - ...

    redis-6.2.14-win-amd64

    Redis是一种开源的、基于键值对的数据存储系统,常用于数据缓存、消息队列以及数据库功能。在Windows环境下,Redis的安装和使用通常需要经过编译和配置过程。"redis-6.2.14-win-amd64"是专门为Windows AMD64架构编译...

    redis 性能测试

    总结起来,进行“redis 性能测试”时,我们需要了解Redis的基本特性和Jedis的使用,通过自定义的测试程序评估Redis在高并发情况下的读取性能,同时根据测试结果进行优化,确保系统的稳定性和高效性。在涉及消息队列...

    java,redis,jedis操作工具类,自己写的简易 demo

    Jedis是Java语言中对Redis官方支持的客户端库,提供了丰富的API来操作Redis服务器。本篇将详细介绍Java使用Jedis进行Redis操作的相关知识点。 1. **Jedis连接池配置** 在实际项目中,为了提高性能和资源利用率,...

    redis存储数据.rar

    Redis是一种高性能的键值对数据存储系统,常用于构建分布式缓存、消息队列和实时数据分析等场景。在Java开发中,我们通常使用Jedis或Lettuce等客户端库来与Redis进行交互。本篇文章将深入探讨如何通过Java代码在...

    tomcat基于redis实现session共享所依赖的jar包

    它提供了各种操作Redis的API,包括读取、写入、删除session数据等。 2. **Apache Commons Lang3**:Apache Commons Lang库提供了一些实用工具类,帮助进行序列化和反序列化操作,将session对象转换为适合在Redis中...

    java 对Redis的导入和导出

    在Java开发中,Redis作为一个高性能的键值存储系统,常被用作缓存或数据库,其数据操作便捷高效。为了在不同的服务器之间迁移或者备份Redis中的数据,我们需要实现数据的导入与导出功能。本篇将详细介绍如何使用Java...

    tomcat+redis依赖包

    这个版本的Jedis提供了丰富的API,支持多种Redis命令,包括字符串、哈希表、列表、集合、有序集合等数据类型的操作,以及事务处理、发布/订阅等功能。通过Jedis,Tomcat可以方便地将会话对象序列化并存储到Redis...

    redis导入到处数据备份

    Redis提供了`redis-cli`命令行工具进行数据导入,但如果你需要在Java程序中操作,可以使用Jedis或Lettuce等Java客户端。例如,你可以通过`keys *`获取所有键,然后遍历每个键并使用`get`命令获取其对应的值,最后将...

    redis 操作文档

    - 使用`get`命令读取数据: ``` get test "helloworld" ``` #### 二、Redis Java调用 通过Java程序调用Redis可以实现更复杂的业务逻辑和自动化管理。接下来介绍两种常见的Java调用方式:简单调用和连接池方式...

    jedis-2.1.0

    2. **全面支持Redis命令:** Jedis几乎实现了Redis的所有命令,包括基本操作以及复杂的事务、发布/订阅、持久化等功能。 3. **连接池支持:** Jedis提供JedisPool,这是一个连接池,可以有效地管理和复用与Redis...

    java大数据作业_8Redis、Thrift、Hadoop2

    AOF(Append Only File)是Redis提供的一种持久化机制,通过记录每一条写入操作的命令来实现数据恢复。 配置步骤如下: 1. 打开Redis配置文件`redis.conf`。 2. 设置`appendonly yes`开启AOF持久化。 3. 配置`...

Global site tag (gtag.js) - Google Analytics