package com.zeekr.hr.recruitment.share.util;
import org.springframework.data.redis.core.RedisTemplate;
import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
public class RedisUtils {
private static RedisTemplate<String, String> redisTemplate;
@Resource
public void setRedisTemplate(RedisTemplate<String, String> redisTemplate) {
RedisUtils.redisTemplate = redisTemplate;
}
public static String getValue(String key) {
return redisTemplate.opsForValue().get(key);
}
public static void setValue(String key, String value, int expire, TimeUnit timeUnit) {
if (expire <= 0) {
redisTemplate.opsForValue().set(key, value);
} else {
redisTemplate.opsForValue().set(key, value, expire, timeUnit);
}
}
public boolean lockOnce(String key, String value, long timeout) {
try {
Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(key, value, timeout, TimeUnit.SECONDS);
return null != aBoolean && aBoolean;
} catch (Exception e) {
return false;
}
}
public boolean deleteKey(String key) {
try {
return Boolean.TRUE.equals(redisTemplate.delete(key));
} catch (Exception e) {
return false;
}
}
}
|