11 Ağustos 2023 Cuma

Lettuce - Redlock İle Distributed Lock

Giriş
Açıklaması şöyle
For mission-critical systems requiring fault-tolerance and consensus, the Redlock algorithm provides a robust solution. Redlock utilises multiple Redis instances across different nodes to achieve consensus.

Use Case: Ideal for scenarios where maintaining distributed locking across multiple Redis nodes is essential, ensuring system-wide resilience. Consider a financial platform that processes transactions across different data centers. The Redlock algorithm ensures that only one data center processes a particular transaction at a time, preventing potential double-spending and maintaining transactional integrity.
Örnek
Şöyle yaparız. Aslında 
io.lettuce.core.api.sync.RedisStringCommands.set(key, value)
io.lettuce.core.api.sync.RedisKeyCommands.del(key) 
kullanılıyor
import io.lettuce.core.RedisClient;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.sync.RedisCommands;
import java.util.concurrent.TimeUnit;

public class RedlockExample {
  public static void main(String[] args) {
    RedisClient client1 = RedisClient.create("redis://localhost:6379");
    RedisClient client2 = RedisClient.create("redis://localhost:6380");
    RedisClient client3 = RedisClient.create("redis://localhost:6381");

    StatefulRedisConnection<String, String> connection1 = client1.connect();
    StatefulRedisConnection<String, String> connection2 = client2.connect();
    StatefulRedisConnection<String, String> connection3 = client3.connect();

    RedisCommands<String, String> redisCommands1 = connection1.sync();
    RedisCommands<String, String> redisCommands2 = connection2.sync();
    RedisCommands<String, String> redisCommands3 = connection3.sync();

    String lockKey = "resource_key";
    String lockValue = "locked";
    long timeout = 300; // Lock expiration time in milliseconds

    long start = System.nanoTime();
    long elapsed = 0;

    try {
      while (elapsed < timeout) {
        if (redisCommands1.set(lockKey, lockValue, "NX", "PX", timeout) != null) {
          // Lock acquired successfully, perform exclusive operations
          // ...
          break;
        }

      TimeUnit.MILLISECONDS.sleep(50);
      elapsed = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start);
    }
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
    } finally {
      redisCommands1.del(lockKey);
      redisCommands2.del(lockKey);
      redisCommands3.del(lockKey);

      connection1.close();
      connection2.close();
      connection3.close();
      client1.shutdown();
      client2.shutdown();
      client3.shutdown();
    }
  }
}

Hiç yorum yok:

Yorum Gönder