RedisTemplate 关于Map的操作实战
一、模板操作的工具类
@Slf4j
@Component
public class RedisTools {
@Autowired
RedisTemplate redisTemplate;
public void delete(String key) {
redisTemplate.delete(key);
}
public Boolean hasKey(String key) {
return redisTemplate.hasKey(key);
}
public Boolean expire(String key, long timeout, TimeUnit unit) {
return redisTemplate.expire(key, timeout, unit);
}
//------------------------------------------ Map的操作 -----------------------------------------------
public void hput(String key, String field, Object object){
redisTemplate.opsForHash().put(key, field, object);
}
public void hPutAll(String key, Map map){
redisTemplate.opsForHash().putAll(key, map);
}
public T hGet(String key, String field, Class clazz ) {
if (!hasKey(key)) {
return null;
}
String mapJson = JSON.toJSONString(redisTemplate.opsForHash().get(key, field));
return JSON.parseObject(mapJson, clazz);
}
public Long hDelete(String key, Object... fields) {
return redisTemplate.opsForHash().delete(key, fields);
}
public Map hGetAll(String key, Class clazz) {
Map
二、项目中使用工具类
根据需求查询一个列表,缓存中有直接取缓存数据,没有就从数据库查询,然后保存到缓存方便下次查询:
//商品列表 ListstandardGoodsCityList = Lists.newlinkedList(); //缓存key String cityListKey = Constant.SEARCH_CITY_LIST + cityQueryAO.getGoodsId(); //根据缓存key查看map值 Map cacheCityMap = redisTools.hGetAll(cityListKey , StandardGoodsCity.class); if (cacheCityMap .size()>1) { standardGoodsCityList = new ArrayList (cacheCityMap .values()); } else { //数据库查询 List citys = standardGoodsCityService.list(new QueryWrapper ().lambda().eq(StandardGoodsCity::getGoodsId, cityQueryAO.getGoodsId())); if (!CollectionUtils.isEmpty(citys)) { for ( StandardGoodsCity standardGoodsCity: citys ) { //按照商品的详情id存入缓存 redisTools.hput(cityListKey , standardGoodsCity.getId().toString(), standardGoodsCity); } //设置缓存的过期时间 redisTools.expire(cityListKey , Constant.ONE, TimeUnit.DAYS); } standardGoodsCityList .addAll(citys); }
三、如果中间新增商品,或者对商品信息进行编辑之后也需要将最新的数据写入最新的缓存列表中
//刷新缓存(新增与编辑相同) StandardGoodsCity standardGoodsCity = standardGoodsCity Service.getOne(new QueryWrapper().lambda().eq(StandardGoodsCity::getSourceGoodsId, sourceGoodsId)); if ( null != standardGoodsCity && redisTools.hasKey(cityListKey)) { redisTools.hput(cityListKey, standardGoodsCity.getId().toString(), standardGoodsCity); }



