实例 DEMO1:
//例如某个Service里面只需要引用RedisTemplate类即可:
@Autowired
private static RedisTemplate redisTemplate;
//某个service方法中,直接调用redisTemplate操作redis的set集合,储存key和value
public Object cacheAround(String key,String value) throws Throwable {
....
//直接调用redisTemplate操作redis的set集合,储存key和value
redisTemplate.opsForSet().add(key,value);
//这里不需要,关心redisTemplate里面配置的是连接池,还是哨兵,还是cluster。
.....
}
DEMO2:通过 RedisTemplate 直接操作 key/value。
//声明
@Resource(name = "redisTemplate")
private RedisTemplate<String, String> template;
//调用方法
template.opsForValue().set("key","value");
DEMO3:通过注入 resdisTemplate 操作 ValueOperations。
//RedisTemplate还提供了对应的*OperationsEditor,用来通过RedisTemplate直接注入对应的Operation。
//声明
@Resource(name = "redisTemplate")
private ValueOperations<String, Object> vOps;
//调用方法
vOps.set("key","value");
DEMO4:通过注解 HashOperations 操作 Hash 数据结构。
//注入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);
DEM5:通过 template 操作 Hash 数据结构。
//注入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);