import com.alibaba.fastjson.JSON; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Component; import java.util.concurrent.TimeUnit; /** * 外部反序列化 * */ @Component public class RedisTools<T> { @Autowired private StringRedisTemplate redisTemplate; /** * 存儲 * * @param key * @param instance 類對象 * @param timeOut 超時時間 單位/小時 */ public void set(String key, T instance, int timeOut){ String value = JSON.toJSONString(instance); redisTemplate.opsForValue().set(key, value, timeOut, TimeUnit.HOURS); } /** * 獲取 * * @param key * @param clazz */ public T get(String key, Class<T> clazz){ String value = redisTemplate.boundValueOps(key).get(); if(value == null) return null; return JSON.parseObject(value, clazz); } }