stingRedisTemplate 使用setNX 设置一个带有过期时间的缓存,同时保证set和给key设置过期时间在一个原子操作下,避免set成功了,但没有给对应的key设置过期时间;

在Spring Data Redis中,StringRedisTemplate是一个用于操作字符串类型的Redis数据的模板类。要实现在一个原子操作下使用setNX设置缓存并给key设置过期时间,可以使用RedisCallbackexecute方法来执行原子操作。

以下是一个示例代码,演示如何使用StringRedisTemplate进行这个原子操作:

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.data.redis.core.script.ScriptCallback;
import org.springframework.data.redis.core.script.ScriptExecutor;
import org.springframework.data.redis.core.script.DefaultScriptExecutor;
import org.springframework.data.redis.core.script.DefaultScriptExecutor;
import org.springframework.data.redis.core.script.ScriptOperation;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;

import java.util.Collections;

@Component
public class RedisAtomicOperation {

    private final StringRedisTemplate stringRedisTemplate;

    public RedisAtomicOperation(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public Boolean setIfNotExistsWithExpiration(String key, String value, long expirationSeconds) {
        // Lua script to perform the atomic operation
        String luaScript = "local success = redis.call('SETNX', KEYS[1], ARGV[1]);" +
                "if success == 1 then " +
                "   redis.call('EXPIRE', KEYS[1], ARGV[2]);" +
                "end;" +
                "return success;";

        // Set up the RedisScript
        RedisScript<Boolean> redisScript = new DefaultRedisScript<>(luaScript, Boolean.class);

        // Prepare script keys and arguments
        String[] keys = {key};
        Object[] args = {value, String.valueOf(expirationSeconds)};

        // Execute the script atomically
        Boolean result = stringRedisTemplate.execute(redisScript, Collections.singletonList(key), value, String.valueOf(expirationSeconds));

        return result;
    }
}

在这个示例中,setIfNotExistsWithExpiration方法使用Lua脚本来执行SETNXEXPIRE命令,保证了两个操作的原子性。你可以在自己的代码中调用这个方法,传递相应的key、value和过期时间参数。如果SETNX成功,即缓存设置成功,就会调用EXPIRE来设置过期时间。

请注意,Lua脚本中的redis.call函数是用于执行Redis命令的。这样的脚本确保了两个操作在一个原子事务中执行,从而避免了在SETNX成功后,但在EXPIRE之前出现故障的情况。

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值