背景:当存放的数据需要key与数据1:1时,可采用散列表的形式,获得值通过key+hKey获取值,方便更新或者删除,得到单独的一个
目录
一、散列表
其实也就是hashMap的一个形式,通过hash算法获取值所在的位置,性能极高,在redis中也支持此数据结构。
二、使用步骤
1:定义出需要存储的数据对象
public class CrmUserRedis {
private String value;
private String label;
private String phone;
private String type;
}
2:list进行转换,建议使用Mapstrust
@Mappings(
value = {
@Mapping(source = "id",target = "value"),
@Mapping(source = "name",target = "label"),
}
)
CrmUserRedis convertPoToRedis(CrmUser user);
3:进行list去重,转换map
redisList = redisList.stream().distinct().collect(Collectors.toList());
Map<String,CrmUserRedis> maps = redisList.stream()
.collect(Collectors.toMap(CrmUserRedis::getValue, Function.identity()));
4:异步开启线程,批量操作,性能极高
原理为springboot项目启动时,会自动创建线程池在栈区,当需要使用时,会自动拿取,即可放入redis中
@Override
@Async
public void saveRedisMap(Map<String, CrmUserRedis> maps) {
redisService.deleteObject(CacheConstants.CRM_USER);
redisService.setCacheMap(CacheConstants.CRM_USER,maps);
}
5:取得单个
redisService.getCacheMapValue(CacheConstants.CRM_USER,redis.getValue())
6:更新,新增单个
hkey有会自动覆盖,没有为新增,建议封装为单独的一个方法
redisService.setCacheMapValue(CacheConstants.CRM_USER,redis.getValue(),redis);
总结:
1:性能极高,保存的value在1kb左右
2:需要自定义存储的对象类型
3:适用于kv1:1的情况