本章将介绍怎样使用 RedisTemplate 类中所有以 ops 开头的方法。其中,ops 是 Operations 的缩写,表示操作。不同的 ops 方法将返回对不同 Redis 对象进行操作的操作接口。例如:opsForList 将返回一个对 Redis 中 list 类型的数据操作的接口 ListOperations。
方法说明如下表:
| 方法定义 | 方法描述 |
| ClusterOperations<K,V> opsForCluster() | 返回集群特定的操作接口 |
GeoOperations<K,V> opsForGeo() | 返回特定于地理空间的操作接口 |
<HK,HV> HashOperations<K,HK,HV> opsForHash() | 返回对哈希值执行的操作接口 |
HyperLogLogOperations<K,V> opsForHyperLogLog() | 返回对 HyperLogLog 的操作接口 |
ListOperations<K,V> opsForList() | 返回对 list 值执行的操作接口 |
SetOperations<K,V> opsForSet() | 返回对 set 值执行的操作接口 |
ValueOperations<K,V> opsForValue() | 返回对简单值(或 Redis 术语中的字符串)执行的操作接口 |
| ZSetOperations<K,V> opsForZSet() | 返回对 zset 值(也称为排序集)执行的操作接口 |
使用 RedisTemplate 返回对 Redis list 类型数据的操作接口,通过该接口操作 Redis list 类型的缓存。代码如下:
package com.hxstrive.redis.list;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest
public class ListOperationsSimple {
/** 注入 RedisTemplate */
@Autowired
private RedisTemplate<String,String> redisTemplate;
@Test
public void contextLoads() {
// 获取 list 类型的 Operations 操作接口
ListOperations<String,String> ops = redisTemplate.opsForList();
// 写入一个 list 缓存,有三个值
ops.leftPushAll("list", "value1", "value2", "value3");
// 获取刚刚写入的 list 缓存
List<String> list = ops.range("list", 0, -1);
for(String str : list) {
System.out.println(str);
}
}
}运行示例程序,输出结果:
value3 value2 value1
注意:在后续章节将更详细介绍各种类型的 Operations 的具体用法。