一个基于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);
    }  
}
相关推荐
qqxhb1 小时前
零基础学Java——第十一章:实战项目 - 桌面应用开发(JavaFX入门)
java·开发语言·javafx
大神薯条老师1 小时前
Python零基础入门到高手8.4节: 元组与列表的区别
开发语言·爬虫·python·深度学习·机器学习·数据分析
z人间防沉迷k1 小时前
堆(Heap)
开发语言·数据结构·笔记·python·算法
hy.z_7771 小时前
【数据结构】链表 LinkedList
java·数据结构·链表
不二狗1 小时前
每日算法 -【Swift 算法】Two Sum 问题:从暴力解法到最优解法的演进
开发语言·算法·swift
炯哈哈1 小时前
【上位机——WPF】Window标签常用属性
开发语言·c#·wpf·上位机
小白学大数据1 小时前
Python爬虫如何应对网站的反爬加密策略?
开发语言·爬虫·python
Akiiiira1 小时前
【数据结构】队列
java·开发语言·数据结构
程序媛学姐1 小时前
Java级联操作:CascadeType的选择与最佳实践
java·开发语言
不知几秋2 小时前
Maven
java·数据库·maven