一个基于RedisTemplate静态工具类

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

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 redisTemplate;

    private static RedisTemplate 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);
    }  
}

你可能感兴趣的:(常用工具,java,开发语言)