redis添加超时设置
redis添加参数的超时设置, 并且需要加锁,一开始是用
redisTemplate.opsForValue().setIfAbsent("key","value",1,TimeUnit.SECONDS);
结果发现这种方式直接会返回空指针错误
所以只能对方法加锁来解决加锁和超时的问题
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;import java.util.concurrent.TimeUnit;@Component
@Slf4j
public class RedisUtils {@Autowiredprivate RedisTemplate<String, String> redisTemplate;public synchronized Boolean add( String redisKey, String value) {Boolean hasKey = addSub(redisKey, value);redisTemplate.expire(redisKey, 20, TimeUnit.SECONDS);return hasKey;}private Boolean addSub(String redisKey, String value) {Boolean hasKey = redisTemplate.hasKey(redisKey);if (!hasKey) {redisTemplate.opsForValue().set(redisKey, value);return true;}return false;}}