关于springboot:SpringBoot-使用-Jedis

4次阅读

共计 1498 个字符,预计需要花费 4 分钟才能阅读完成。

前置条件

1、开启 Redis 服务器,命令行执行 redis-server.exe。
2、创立 SpringBoot 工程,在引入根本的依赖之外,还须要额定引入:

<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>4.2.3</version>
</dependency>

应用 Redis 的五种数据类型

前置条件

连贯 Redis 服务器并测试通过:

Jedis jedis = new Jedis("localhost");
System.out.println(jedis.ping());

// 输入:PONG

字符串(String)

根本的 get & set 办法应用:

jedis.set("myKey", "myValue");
System.out.println(jedis.get("myKey"));

// 输入://myValue

其余的罕用办法参考:Redis String 命令。

哈希(Hash)

根本的 hmset & hget & hgetAll 办法应用:

Map<String, String> map = new HashMap<>();
map.put("mapKey1", "mapValue1");
map.put("mapKey2", "mapValue2");
map.put("mapKey3", "mapValue3");
jedis.hmset("myMap", map);
System.out.println(jedis.hget("myMap", "mapKey1"));
System.out.println(jedis.hgetAll("myMap").toString());

// 输入://mapValue1
//{mapKey2=mapValue2, mapKey1=mapValue1, mapKey3=mapValue3}

其余罕用办法参考:Redis Hash 命令。

列表(List)

根本的 lpush & lindex & lrange 办法的应用:

jedis.lpush("myList", "1", "2", "3", "A", "B", "C");
System.out.println(jedis.lindex("myList", 1));
System.out.println(jedis.lrange("myList", 0, 2));

// 输入://B
//[C, B, A]

留神:lpush 是将一个或多个值插入到列表头部。
其余罕用办法参考:Redis List 命令。

汇合(Set)

根本的 sadd 和 smembers 办法的应用:

jedis.sadd("mySet", "a", "b", "c", "d", "e");
System.out.println(jedis.smembers("mySet"));

// 输入://[d, a, c, b, e]

留神:Set 是无序汇合。
其余罕用办法参考:Redis Set 命令。

有序汇合(sorted set)

根本的 zadd & zrange 办法的应用:

jedis.zadd("mySortedSet", 2, "b");
jedis.zadd("mySortedSet", 3, "c");
jedis.zadd("mySortedSet", 1, "a");
System.out.println(jedis.zrange("mySortedSet", 0, 2));

// 输入://[a, b, c]

留神:
1、增加时须要指定一个 score,汇合就是通过这个 score 从低到高进行排序。
2、排序好的汇合寄存的起始下标从 0 开始。
其余罕用办法参考:Redis sorted set 命令。

正文完
 0