Distributed Lock iki şekilde gerçekleştirilebilir
1. Redis
2. JDBC
Redis
Maven
Şu satırı dahil ederiz
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-integration</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency><dependency><groupId>org.springframework.integration</groupId><artifactId>spring-integration-redis</artifactId></dependency><dependency><groupId>io.lettuce</groupId><artifactId>lettuce-core</artifactId></dependency>
RedisLockRegistry sınıfı kullanılır
JDBC
Maven
Açıklaması şöyle
The JDBC version of the distributed lock needs the database to have some tables and indexes set up in order to work. If you do not set these up the first time you attempt to obtain the lock, a JDBC Exception will be thrown. The current collection of SQL files for this can be found in the Spring Integration JDBC github repo.
In the following example, Flyway runs the SQL script automatically.
Şu satırı dahil ederiz
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-integration</artifactId> </dependency> <dependency> <groupId>org.springframework.integration</groupId> <artifactId>spring-integration-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> </dependency> <dependency> <groupId>org.flywaydb</groupId> <artifactId>flyway-core</artifactId> </dependency>
Genel Kullanım
Elimizde şöyle bir kod olsun
public interface LockService { String lock(); void failLock(); String properLock(); } @Service public class RedisLockService implements LockService{ private static final String MY_LOCK_KEY = "someLockKey"; private final LockRegistry lockRegistry; public RedisLockService(LockRegistry redisLockRegistry) { this.lockRegistry = redisLockRegistry; } } @Service public class JDBCLockService implements LockService{ private static final String MY_LOCK_KEY = "someLockKey"; private final LockRegistry lockRegistry; public JDBCLockService(JdbcLockRegistry jdbcLockRegistry) { this.lockRegistry = jdbcLockRegistry; } }
Şöyle yaparız. obtain() ile bir Lock nesnesi elde edilir. tryLock() ile bu kilitlenir.
a@Override public String lock() { Lock lock = null; String returnVal = null; try { lock = lockRegistry.obtain(MY_LOCK_KEY); if (lock.tryLock()) { returnVal = "lock successful"; } else { returnVal = "lock unsuccessful"; } } catch (Exception e) { ... } finally { if (lock != null) { lock.unlock(); } } return returnVal; }
Hiç yorum yok:
Yorum Gönder