由于项目中大量使用stringRedisTemplate的hash操作,我们规定key和value都使用String类型。但是由于有些返回值不是String类型,就导致每次需要强制类型转换。例如如下操作:
@Resource
private StringRedisTemplate stringRedisTemplate;
public void redisHashOperation() {
Map<Object, Object> entries = stringRedisTemplate.opsForHash().entries("");
}
返回值Map的Key和value都是Object类型的,要使用的话基本需要自己做强制类型转换,万一存在空值还容易导致空指针异常。使用起来繁琐且容易出bug。
于是,leader教了一手(网上查询了一番,基本都是教了些简单使用,涉及hash操作基本都是强转的),如下:
@Resource
private StringRedisTemplate stringRedisTemplate;
public void redisHashOperation() {
Map<String, String> entries = stringRedisTemplate.<String, String>opsForHash().entries("");
}
指定hash的键值为String,优雅。