每次是用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);
}
}