1. 程式人生 > 實用技巧 >清單:在ASP.NET中不能做什麼

清單:在ASP.NET中不能做什麼

@RestController
public class RedisLock {
@Resource
RedisTemplate<String, Object> redisTemplate;

@GetMapping("lock/{key}/{value}")
public String testLock(@PathVariable String key, @PathVariable String value) {
     // 根據key獲取分散式鎖,並且設定過期時間

Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(key, value, 10, TimeUnit.SECONDS);


if (aBoolean) {
try {
System.out.println("獲取到鎖");
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
Boolean unlock = unlockLua(key, value);
System.out.println(unlock);

}
} else {
System.out.println("未獲取到鎖");
}
return "測試鎖";
}

public boolean unlockLua(String key, String value) {
DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
//用於解鎖的lua指令碼位置
redisScript.setLocation(new ClassPathResource("unlock.lua"));

redisScript.setResultType(Long.class);
//沒有指定序列化方式,預設使用上面配置的
Object result = redisTemplate.execute(redisScript, Collections.singletonList(key), value);
assert result != null;
return result.equals(1L);
}
//
在resources中建立 unlock.lua 加入以下程式碼

if redis.call('get',KEYS[1]) == ARGV[1] then
return redis.call('del',KEYS[1])
else
return 0
end


}