一个基于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);
    }  
}
相关推荐
yuweiade1 小时前
【Spring】Spring MVC案例
java·spring·mvc
free-elcmacom1 小时前
C++ 默认参数详解:用法、规则与避坑指南
开发语言·c++
码云数智-大飞1 小时前
分布式事务解决方案全景指南:2PC、TCC、SAGA 与 Seata 实战
开发语言
娇娇yyyyyy1 小时前
QT编程(10): QLineEdit
开发语言·qt
Albert Edison1 小时前
【ProtoBuf 语法详解】Any 类型
服务器·开发语言·c++·protobuf
喵叔哟2 小时前
5. 【Blazor全栈开发实战指南】--Blazor组件基础
开发语言·javascript·ecmascript
罗超驿2 小时前
Java数据结构_链表
java·数据结构·链表
海奥华22 小时前
Rust初步学习
开发语言·学习·rust
小璐资源网2 小时前
C++中如何正确区分`=`和`==`的使用场景?
java·c++·算法
卢锡荣2 小时前
LDR6021Q 车规级 Type‑C PD 控制芯片:一芯赋能,边充边传,稳驭全场景
c语言·开发语言·ios·计算机外设·电脑