Java 使用 Jedis 操作 Redis 各种数据类型详解
在现代应用中,Redis 已成为高性能缓存与数据存储的重要工具。本文将通过 Java 中广泛使用的 Jedis 客户端,系统性地介绍如何操作 Redis 支持的多种数据结构,包括:
- String(字符串)
- List(列表)
- Set(集合)
- Hash(哈希)
- ZSet(有序集合)
- Bitmap(位图)
- HyperLogLog(基数估计)
- Stream(流)
- Geospatial(地理位置)
- Pub/Sub(发布订阅)
本文不仅涵盖每种数据类型的基本操作,还附带完整示例代码和注释,方便开发者快速掌握 Jedis 的使用方法。
一、环境准备
Maven 引入 Jedis 依赖
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>4.0.0</version>
</dependency>
二、连接 Redis
import redis.clients.jedis.Jedis;
public class RedisExample {
public static void main(String[] args) {
// 连接到本地 Redis 服务
Jedis jedis = new Jedis("localhost");
System.out.println("Connection to server successfully");
// 检查 Redis 服务是否可用
System.out.println("Server is running: " + jedis.ping());
}
}
三、数据类型操作
1. String(字符串)
字符串是 Redis 中最基本的数据类型,支持设置、获取、追加、递增等操作。
// 设置字符串
jedis.set("name", "Alice");
// 获取字符串
String name = jedis.get("name");
System.out.println("Stored string in redis: " + name);
// 递增操作
jedis.set("counter", "1");
jedis.incr("counter");
String counter = jedis.get("counter");
System.out.println("Counter value in redis: " + counter);
// 追加操作
jedis.append("name", " Wonderland");
String fullName = jedis.get("name");
System.out.println("Full name in redis: " + fullName);
// 获取字符串长度
long length = jedis.strlen("name");
System.out.println("Length of 'name': " + length);
2. List(列表)
列表是一种链表结构,支持从头部或尾部插入和移除元素。
// 将值插入列表
jedis.lpush("fruits", "apple");
jedis.lpush("fruits", "banana");
jedis.rpush("fruits", "cherry");
// 获取列表中的所有值
List<String> fruits = jedis.lrange("fruits", 0, -1);
System.out.println