RedisTemplate 类中的所有以 bound 前缀开头的方法,将会返回一个绑定到指定键上的 Operations 操作接口,且该接口只能操作绑定到该 Operations 上的键,不能对其他键进行操作。例如:
BoundListOperations<String,String> ops = redisTemplate.boundListOps("list_name");上述代码中,ops 对象只能对键名称为 list_name 的缓存进行操作,不能对其他键进行操作。这是因为,Bound 类型的所有 Operations 对象中定义的方法均不接受参数“缓存键”。
方法说明如下表:
| 方法定义 | 方法描述 |
| BoundGeoOperations<K,V> boundGeoOps(K key) | 返回绑定到给定键的地理空间特定操作接口 |
| <HK,HV> BoundHashOperations<K,HK,HV> boundHashOps(K key) | 返回对绑定到给定键的 hash 值执行的操作 |
| BoundListOperations<K,V> boundListOps(K key) | 返回对绑定到给定键的 list 值执行的操作 |
| BoundSetOperations<K,V> boundSetOps(K key) | 返回对绑定到给定键的 set 值执行的操作 |
| BoundValueOperations<K,V> boundValueOps(K key) | 返回对绑定到给定键的简单值(或 Redis 术语中的字符串)执行的操作 |
| BoundZSetOperations<K,V> boundZSetOps(K key) | 返回对绑定到给定键的 zset 值(也称为排序集)执行的操作 |
下面还是以 Redis 中 list 类型为例,通过 boundListOps() 方法获取 BoundListOperations 操作接口,使用该接口快捷的操作 Redis 的 list 类型的缓存。代码如下:
package com.hxstrive.redis.bound;
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.BoundListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest
public class ListBoundOpsSimple {
/** 注入 RedisTemplate */
@Autowired
private RedisTemplate<String,String> redisTemplate;
@Test
public void contextLoads() {
// 获取 list 类型的 Operations 操作接口
BoundListOperations<String,String> ops = redisTemplate.boundListOps("list");
// 向键等于 list 的缓存写入 “hello” 和 “world” 两个字符串
ops.leftPushAll("hello", "world");
// 获取键等于 list 的缓存的所有内容
List<String> listValues = ops.range(0, -1);
for(String str : listValues) {
System.out.println(str);
}
}
}运行示例代码,输出结果如下:
world hello value3 value2 value1
细心的读者可以看到,上面在调用 leftPushAll() 和 range() 方法时,并没有传递要操作的缓存键,缓存键在获取该 ops 对象时已经传递,即缓存键和该ops进行了绑定,因此这些 Operations 才称为 Bound。