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