一个基于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);
    }  
}
相关推荐
2501_941111694 分钟前
C++中的枚举类高级用法
开发语言·c++·算法
chilavert31810 分钟前
技术演进中的开发沉思-191 JavaScript: 发展历程(上篇)
开发语言·javascript·ecmascript
q***615015 分钟前
eclipse配置Spring
java·spring·eclipse
Miraitowa_cheems30 分钟前
LeetCode算法日记 - Day 106: 两个字符串的最小ASCII删除和
java·数据结构·算法·leetcode·深度优先
q***581932 分钟前
Spring全家桶简介
java·后端·spring
l1t42 分钟前
调用python函数的不同方法效率对比测试
开发语言·数据库·python·sql·duckdb
武昌库里写JAVA43 分钟前
微擎服务器配置要求,微擎云主机多少钱一年?
java·vue.js·spring boot·后端·sql
IUGEI1 小时前
深入解析HTTP长连接原理
java·网络·后端·网络协议·tcp/ip·http·https
q***64971 小时前
头歌答案--爬虫实战
java·前端·爬虫