RedisTemplate 关于Map的操作实战

一、模板操作的工具类

@Slf4j
@Component
public class RedisTools {

    @Autowired
    RedisTemplate redisTemplate;

    /**
     * 删除key
     * @param key
     */
    public void delete(String key) {
        redisTemplate.delete(key);
    }

    /**
     * 是否存在key
     * @param key
     * @return
     */
    public Boolean hasKey(String key) {
        return redisTemplate.hasKey(key);
    }

    /**
     * 设置过期时间
     * @param key
     * @param timeout
     * @param unit
     * @return
     */
    public Boolean expire(String key, long timeout, TimeUnit unit) {
        return redisTemplate.expire(key, timeout, unit);
    }

    //------------------------------------------ Map的操作 -----------------------------------------------

    /**
     *  保存map值到指定key
     */
    public void hput(String key, String field, Object object){
        redisTemplate.opsForHash().put(key, field, object);
    }

    /**
     * 保存多个key-value的map
     */
    public <T> void hPutAll(String key, Map<String,T> map){
        redisTemplate.opsForHash().putAll(key, map);
    }

    /**
     * 获取存储在哈希表中指定字段的值
     * @param key
     * @param field
     * @return
     */
    public <T> T hGet(String key, String field, Class<T> clazz ) {
        if (!hasKey(key)) {
            return null;
        }
        String mapJson = JSON.toJSONString(redisTemplate.opsForHash().get(key, field));
        return JSON.parseObject(mapJson, clazz);
    }

    /**
     * 删除一个或多个哈希表字段
     *
     * @param key
     * @param fields
     * @return
     */
    public Long hDelete(String key, Object... fields) {
        return redisTemplate.opsForHash().delete(key, fields);
    }


    /**
     * 获取一个map集
     * @param key 名
     * @param clazz 返回的map-value的值类型
     * @param <E>
     * @return
     */
   	 public <E> Map<String, E> hGetAll(String key, Class<E> clazz) {
	        Map<Object, Object> entries = redisTemplate.opsForHash().entries(key);
	        if(entries==null || entries.size()==0){
	            return Collections.emptyMap();
	        }
	        Map<String, E> resultMap = new LinkedHashMap<>(entries.size());
	        for(Map.Entry<Object,Object> entry : entries.entrySet()){
	            E valueObj = JSON.parseObject(JSON.toJSONString(entry.getValue()), clazz );
	            String hashKey = JSON.toJSONString(entry.getKey());
	            if (hashKey == null) {
	                return null;
	            }
	            hashKey = hashKey.replace("\"", "");
	            resultMap.put(hashKey, valueObj);
	        }
	        return resultMap;
	    }
    }

二、项目中使用工具类
根据需求查询一个列表,缓存中有直接取缓存数据,没有就从数据库查询,然后保存到缓存方便下次查询:

//商品列表
List<StandardGoodsCity> standardGoodsCityList = Lists.newLinkedList();
//缓存key
String cityListKey = Constant.SEARCH_CITY_LIST + cityQueryAO.getGoodsId();
//根据缓存key查看map值
Map<String,StandardGoodsCity> cacheCityMap = redisTools.hGetAll(cityListKey , StandardGoodsCity.class);
if (cacheCityMap .size()>1) {
    standardGoodsCityList = new ArrayList<StandardGoodsCity>(cacheCityMap .values());
} else {
    //数据库查询
    List<StandardGoodsCity> citys = standardGoodsCityService.list(new QueryWrapper<StandardGoodsCity>().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<StandardGoodsCity>().lambda().eq(StandardGoodsCity::getSourceGoodsId, sourceGoodsId));
if ( null != standardGoodsCity && redisTools.hasKey(cityListKey)) {
    redisTools.hput(cityListKey, standardGoodsCity.getId().toString(), standardGoodsCity);
}
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐