一个基于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);
    }  
}
相关推荐
Gerardisite8 分钟前
如何在微信个人号开发中有效管理API接口?
java·开发语言·python·微信·php
Want59510 分钟前
C/C++跳动的爱心①
c语言·开发语言·c++
coderxiaohan39 分钟前
【C++】多态
开发语言·c++
gfdhy1 小时前
【c++】哈希算法深度解析:实现、核心作用与工业级应用
c语言·开发语言·c++·算法·密码学·哈希算法·哈希
闲人编程1 小时前
Python的导入系统:模块查找、加载和缓存机制
java·python·缓存·加载器·codecapsule·查找器
Eiceblue1 小时前
通过 C# 将 HTML 转换为 RTF 富文本格式
开发语言·c#·html
故渊ZY1 小时前
Java 代理模式:从原理到实战的全方位解析
java·开发语言·架构
匿者 衍1 小时前
POI读取 excel 嵌入式图片(支持wps 和 office)
java·excel
leon_zeng01 小时前
Qt Modern OpenGL 入门:从零开始绘制彩色图形
开发语言·qt·opengl
会飞的胖达喵1 小时前
Qt CMake 项目构建配置详解
开发语言·qt