SimpleRedisLock extends AbstractSimpleLock { @Override protected String acquire(final String key, final String storeId, final String token, final long expiration) { final var singletonKeyList = Collections.singletonList(storeId + ":" + key); final var locked = stringRedisTemplate.execute(lockScript, singletonKeyList, token, String.valueOf(expiration)); log.debug("Tried to acquire lock for key {} with token {} in store {}. Locked: {}", key, token, storeId, locked); return locked ? token : null; } SimpleRedisLock(final Supplier<String> tokenSupplier, final StringRedisTemplate stringRedisTemplate);   }
@Test public void shouldLock() { final String token = lock.acquire(Collections.singletonList("1"), "locks", 1000); assertThat(token).isEqualTo("abc"); assertThat(redisTemplate.opsForValue().get("locks:1")).isEqualTo("abc"); assertThat(redisTemplate.getExpire("locks:1", TimeUnit.MILLISECONDS)).isCloseTo(1000, Offset.offset(100L)); }
@Test public void shouldNotLock() { redisTemplate.opsForValue().set("locks:1", "def"); final String token = lock.acquire(Collections.singletonList("1"), "locks", 1000); assertThat(token).isNull(); assertThat(redisTemplate.opsForValue().get("locks:1")).isEqualTo("def"); }
@Test public void shouldExpire() throws InterruptedException { lock.acquire(Collections.singletonList("1"), "locks", 100); Thread.sleep(100); assertThat(redisTemplate.opsForValue().get("locks:1")).isNull(); }