在 Spring Data Redis 中,如果要向 Redis Stream 发送记录。可以与其他操作一样,使用低级 RedisConnection 或高级 StreamOperations 类来实现。
RedisConnection 和 StreamOperations 两个类都提供 add(xAdd)方法,该方法接受记录(record)和目标流(stream)作为参数。虽然 RedisConnection 需要原始数据(字节数组),但 StreamOperations 允许将任意对象作为记录(record)传入。
由于 Redis Stream 是 Redis 5.0 版本新增加的数据结构。因此,Spring Boot 需要更高的 Spring Data Redis 版本才能使用 Redis Stream,添加如下依赖:
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.5.6</version> <relativePath/> <!-- lookup parent from repository --> </parent>
创建一个简单的 @SpringBootTest 测试类,代码如下:
@Test
public void contextLoads() {
System.out.println("redisTemplate = " + redisTemplate);
redisTemplate.execute(new RedisCallback<String>() {
@Override
public String doInRedis(RedisConnection connection) throws DataAccessException {
// Redis Stream 的键名
byte[] stream = "myStream".getBytes();
// Redis Stream 的数据
Map<byte[],byte[]> map = new HashMap<>();
map.put("title".getBytes(), "Redis Streams".getBytes());
map.put("version".getBytes(), "v1.0.0".getBytes());
map.put("summary".getBytes(),
"Redis Streams model a log data structure in an abstract approach.".getBytes());
// 将 Redis Stream 写入到 Redis
MapRecord<byte[], byte[], byte[]> mapRecord =
StreamRecords.rawBytes(map).withStreamKey(stream);
connection.xAdd(mapRecord);
return null;
}
});
}运行上面示例,然后利用 redis-cli 命令连接到 Redis 服务器。使用 xrange 命令查询刚刚写入的 Redis Stream 数据,如下:
D:\server\redis-x64-5.0.14.1>redis-cli 127.0.0.1:6379[2]> select 1 OK 127.0.0.1:6379[1]> xrange myStream - + 1) 1) "1666331433947-0" 2) 1) "version" 2) "v1.0.0" 3) "title" 4) "Redis Streams" 5) "summary" 6) "Redis Streams model a log data structure in an abstract approach." 127.0.0.1:6379[1]>
注意,上面的“select 1”语句用来选择下标为1的数据库,“xrange myStream - +”命令用来获取 Key 为 myStream 的 Redis Stream 中的数据。
下面演示使用 RedisTemplate 高级类向 Redis Stream 中添加数据,代码如下:
@Test
public void contextLoads() {
System.out.println("redisTemplate = " + redisTemplate);
StreamOperations<String,byte[], byte[]> ops = redisTemplate.opsForStream();
// Redis Steam 键
String key = "myStream";
// Redis Stream 内容
Map<byte[],byte[]> map = new HashMap<>();
map.put("title".getBytes(), "Redis Streams".getBytes());
map.put("version".getBytes(), "v1.0.0".getBytes());
map.put("summary".getBytes(),
"Redis Streams model a log data structure in an abstract approach.".getBytes());
// 添加到 Redis Stream
ops.add(key, map);
}运行示例,然后利用 redis-cli 命令连接到 Redis 服务器。使用 xrange 命令查询刚刚写入的 Redis Stream 数据,如下:
D:\server\redis-x64-5.0.14.1>redis-cli 127.0.0.1:6379> select 1 OK 127.0.0.1:6379[1]> xrange myStream - + 1) 1) "1666366851342-0" 2) 1) "title" 2) "Redis Streams" 3) "version" 4) "v1.0.0" 5) "summary" 6) "Redis Streams model a log data structure in an abstract approach." 127.0.0.1:6379[1]>