PROGRAMMING/JAVA

redis watch/multi example

OJR 2023. 3. 11. 20:43
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;
                }
            }
        });
    }
}
반응형