import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;
@Component
public class RedisWatchExample {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
public String getValueOrSetIfNotExists(String key, String value, int ttl) {
return (String) redisTemplate.execute(new SessionCallback<Object>() {
@Override
public Object execute(RedisOperations redisOperations) throws DataAccessException {
redisOperations.watch(key);
String currentValue = (String) redisOperations.opsForValue().get(key);
if (currentValue == null) {
redisOperations.multi();
redisOperations.opsForValue().set(key, value);
redisOperations.expire(key, ttl, TimeUnit.SECONDS);
redisOperations.exec();
return value;
} else {
redisOperations.unwatch();
return currentValue;
}
}
});
}
}
반응형
'PROGRAMMING > JAVA' 카테고리의 다른 글
Spring Boot Interceptor를 특정 URL에 적용 방법 (0) | 2023.04.03 |
---|---|
Eclipse(Galileo) 에 SVN Client 설치하기 & 이클립스 svn 메뉴설명 (0) | 2014.07.30 |
[토비의 스프링 3.0] 1 장 오브젝트와 의존관계 (0) | 2013.02.20 |
날짜 구하기 (0) | 2013.01.10 |
maven (0) | 2013.01.09 |