Redis教程

超强Redis数据类型与应用场景总结!!(含完整实战案例,建议收藏)

本文主要是介绍超强Redis数据类型与应用场景总结!!(含完整实战案例,建议收藏),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

本文全面讲述了Redis的五大数据类型和使用场景,含完整实战案例,建议收藏!!

大家好,我是冰河~~

最近面试跳槽的小伙伴有点多,给我反馈的面试情况更是千差万别,不过很多小伙伴反馈说:面试中的大部分问题都能够在我的CSDN博客中找到答案,面试过程还是挺轻松的,最终也是轻松的拿到了Offer!听到这些,我也确实替小伙伴们高兴!

今天,在安排一篇Redis技术干货。如果文章对你有点帮助,小伙伴们点赞、收藏、评论、分享走起呀~~

好了,开始今天的正文~~

关于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五大数据类型的完整测试代码。

分类代码:

  • 获取Jedis句柄
private static Jedis jedis;
static {
    jedis = new Jedis("192.168.175.100", 6379);
    jedis.auth("123456"); // 之前我在redis配置中配置了权限密码,这里需要设置
}
  • key-value数据
/**
  * 测试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集合
/***
  * 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中没有
}
  • Hash散列
/***
  * 散列
  */
@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));
}

完整代码:

package com.binghe.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.175.100", 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五大数据类型的完整源码。

分类代码

  • 获取JedisCluster句柄
private static JedisCluster jedis;
static {
    // 添加集群的服务节点Set集合
    Set<HostAndPort> hostAndPortsSet = new HashSet<HostAndPort>();
    // 添加节点
    hostAndPortsSet.add(new HostAndPort("192.168.175.100", 7777));
    hostAndPortsSet.add(new HostAndPort("192.168.175.100", 8888));
    hostAndPortsSet.add(new HostAndPort("192.168.175.101", 7777));
    hostAndPortsSet.add(new HostAndPort("192.168.175.101", 8888));
    hostAndPortsSet.add(new HostAndPort("192.168.175.102", 7777));
    hostAndPortsSet.add(new HostAndPort("192.168.175.102", 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数据
/**
  * 测试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集合
/***
  * 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");
}
  • Hash散列
/***
  * 散列
  */
@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));*/
}

完整代码

package com.binghe.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.175.100", 7777));
        hostAndPortsSet.add(new HostAndPort("192.168.175.100", 8888));
        hostAndPortsSet.add(new HostAndPort("192.168.175.101", 7777));
        hostAndPortsSet.add(new HostAndPort("192.168.175.101", 8888));
        hostAndPortsSet.add(new HostAndPort("192.168.175.102", 7777));
        hostAndPortsSet.add(new HostAndPort("192.168.175.102", 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));*/
    }
}

小伙伴们记得点赞、收藏、评论、分享呀~~

好了,今天就到这儿吧,我是冰河,大家有啥问题可以在下方留言,一起交流技术,一起进阶,一起进大厂~~

这篇关于超强Redis数据类型与应用场景总结!!(含完整实战案例,建议收藏)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!