在RedisTemplate中提供了几个常用的接口方法的使用,分别是:
private ValueOperations<K, V> valueOps;
private ListOperations<K, V> listOps;
private SetOperations<K, V> setOps;
private ZSetOperations<K, V> zSetOps;
ValueOperations
这个接口的实现类为:DefaultValueOperations.
在RedisTemplate中,已经提供了一个工厂方法:opsForValue()。这个方法会返回一个默认的操作类。另外,我们可以直接通过注解@Resource(name = “redisTemplate”)来进行注入。
//声明
@Resource(name = "redisTemplate")
private RedisTemplate<String, String> template;
//调用方法
template.opsForValue().set("key","value");
HashOperations接口说明
这个接口并没有定义成员变量,但是直接提供了方法。
public <HK, HV> HashOperations<K, HK, HV> opsForHash() {
return new DefaultHashOperations<K, HK, HV>(this);
}
- 具体的调用如下:
方法1
//注入HashOperations对象
@Resource(name = "redisTemplate")
private HashOperations<String,String,Object> hashOps;
//具体调用
Map<String,String> map = new HashMap<String, String>();
map.put("value","code");
map.put("key","keyValue");
hashOps.putAll("hashOps",map);
方法2
//注入RedisTemplate对象
@Resource(name = "redisTemplate")
private RedisTemplate<String, String> template;
//具体调用
Map<String,String> map = new HashMap<String, String>();
map.put("value","code");
map.put("key","keyValue");
template.opsForHash().putAll("hashOps",map);