@Component public class RedisUtils { @Autowired private RedisTemplate<String, Object> redisTemplate; @Autowired private ValueOperations<String, String> valueOperations; @Autowired private HashOperations<String, String, Object> hashOperations; @Autowired private ListOperations<String, Object> listOperations; @Autowired private SetOperations<String, Object> setOperations; @Autowired private ZSetOperations<String, Object> zSetOperations; /** 默认过期时长,单位:秒 */ public final static long DEFAULT_EXPIRE = 60 * 60 * 24; /** 不设置过期时长 */ public final static long NOT_EXPIRE = -1; private final static Gson gson = new Gson(); public void set(String key, Object value, long expire){ //通过ValueOperations设置值 valueOperations.set(key, toJson(value)); if(expire != NOT_EXPIRE){ //设置key的失效时间 redisTemplate.expire(key, expire, TimeUnit.SECONDS); } } /** * set存数据 * @param key * @param value */ public void set(String key, Object value){ set(key, value, DEFAULT_EXPIRE); } public <T> T get(String key, Class<T> clazz, long expire) { //通过ValueOperations获取值 String value = valueOperations.get(key); if(expire != NOT_EXPIRE){ //设置key的失效时间 redisTemplate.expire(key, expire, TimeUnit.SECONDS); } return value == null ? null : fromJson(value, clazz); } /** * get获取数据 * @param key * @param clazz * @param <T> * @return */ public <T> T get(String key, Class<T> clazz) { return get(key, clazz, NOT_EXPIRE); } public String get(String key, long expire) { String value = valueOperations.get(key); if(expire != NOT_EXPIRE){ redisTemplate.expire(key, expire, TimeUnit.SECONDS); } return value; } /** * get获取数据 * @param key * @return */ public String get(String key) { return get(key, NOT_EXPIRE); } public void delete(String key) { //删除单个key redisTemplate.delete(key); } /** * Object转成JSON数据 */ private String toJson(Object object){ if(object instanceof Integer || object instanceof Long || object instanceof Float || object instanceof Double || object instanceof Boolean || object instanceof String){ return String.valueOf(object); } return gson.toJson(object); } /** * JSON数据,转成Object */ private <T> T fromJson(String json, Class<T> clazz){ return gson.fromJson(json, clazz); } }
一个小小后端的爬行痕迹
今天的文章redis连接工具_java常用的类分享到此就结束了,感谢您的阅读,如果确实帮到您,您可以动动手指转发给其他人。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/51607.html