一个基于RedisTemplate静态工具类

每次是用RedisTemplate的时候都需要进行自动注入实在是太麻烦了,于是找到一个讨巧的办法。

java 复制代码
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.TimeUnit;

/**
 * @author admin
 */
@Component
public class RedisUtil {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    private static RedisTemplate<String,String> redisTemp;

    @PostConstruct
    public void initRedisTem(){
        redisTemp = redisTemplate;
    }

    public static void set(String key, String value,int timeout, TimeUnit timeUnit) {
        redisTemp.opsForValue().set(key, value);
    }  
  
    public static String get(String key) {  
        return redisTemp.opsForValue().get(key);
    }  
  
    public static boolean tryLock(String lockKey, int timeout, TimeUnit timeUnit) {
        return Boolean.TRUE.equals(redisTemp.opsForValue().setIfAbsent(lockKey, "locked", timeout, timeUnit));
    }  
  
    public static void unlock(String lockKey) {
        redisTemp.delete(lockKey);
    }  
}
相关推荐
廋到被风吹走16 小时前
【MySql】超时问题分析
java·数据库·mysql
云创智城-yuncitys16 小时前
[特殊字符]⚡ 停充一体化云平台:基于微服务架构的城市智慧停车+新能源充电解决方案
java·微服务·架构
csbysj202016 小时前
Python break 语句详解
开发语言
毕设源码-朱学姐16 小时前
【开题答辩全过程】以 高效便捷的民航订票系统为例,包含答辩的问题和答案
java
2401_8579182916 小时前
C++中的访问者模式实战
开发语言·c++·算法
格林威16 小时前
工业相机图像高速存储(C++版):RAID 0 NVMe SSD 阵列暴力提速,附海康实战代码!
开发语言·c++·人工智能·数码相机·计算机视觉·工业相机·堡盟相机
零雲16 小时前
java面试:Spring事务失效的场景有哪些?
java·数据库·面试
二月十六16 小时前
运行 ‘XXXX‘ 时出错 运行 XXXX时出错。命令行过长。 通过 JAR 清单或通过类路径文件缩短命令行,然后重新运行。
java·jar
elseif12316 小时前
CSP-S提高级大纲
开发语言·数据结构·c++·笔记·算法·大纲·考纲
波特率11520016 小时前
C++中类的const与static关键字修饰函数与变量辨析
开发语言·c++·