package com.zzwtec.third.config.redis; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.TypeReference; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; import java.util.concurrent.TimeUnit; /** * create by Jomchen on 2018/12/4 * redis 操作工具,建义存redis 用此工具 */ @Service public class RedisService { @Autowired @Qualifier("stringRedisTemplate") private RedisTemplate stringRedisTemplate; /** * 把对象序列化成字符串放入 redis * 建议这样做,可以减少很多的类型转换问题,且达到统一标准 */ public void saveEntityToJson(String key, Object obj, long expire, TimeUnit timeUnit) { String value = JSONObject.toJSONString(obj); stringRedisTemplate.opsForValue().set(key, value); if (expire > 0) { stringRedisTemplate.expire(key, expire, timeUnit); } } /** * 为数据设置缓存时间 */ public boolean expire(String key, long expire, TimeUnit timeUnit) { return stringRedisTemplate.expire(key, expire, timeUnit); } /** * 获取对象 */ public T getEntity(String key, TypeReference typeReference) { String json = stringRedisTemplate.opsForValue().get(key); if (null == json) { return null; } T result = JSONObject.parseObject(json, typeReference); return result; } public void delete(String key) { stringRedisTemplate.delete(key); } }