Java Cluster Combat: Upgrading Single Architecture to Cluster Architecture (5) Scheduled Tasks
We still start with this picture:
This picture is used in "Java Cluster Combat: Upgrading Monolithic Architecture to Cluster Architecture (1) Using NGINX to Build a Cluster". If you use synchronized and lock in your code, they run well in a single application, but they are not easy to use in a cluster environment, because they can only lock their own tomcat and cannot lock other tomcats. At this time, synchronized and lock should be changed to distributed locks. Common distributed locks include optimistic locks and pessimistic locks of databases, zookeeper distributed locks, etcd distributed locks, redis distributed locks, etc. We have used redis to save sessions before, so today we will use redis distributed locks again.
GitHub: GitHub - all the source code of Dengxd/JavaCluster is here, GitHub often cannot be connected, so it needs to be refreshed several times
First introduce redisson in pom.xml:
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson</artifactId>
<version>3.20.0</version>
</dependency>
Then create a bean:
@Configuration
public class Configure {
@Bean
public RedissonClient redissonClient() {
Config config = new Config();
// use "rediss://" for SSL connection
config.useSingleServer().setAddress("redis://127.0.0.1:6379");
RedissonClient redisson = Redisson.create(config);
return redisson;
}
}
In this way, redissonClient can be used for locking operations
The main locking code is also very simple:
RLock lock = redissonClient.getLock("TicketLock");//建立锁
try {
lock.lock();//锁住资源
//在这里写您要做的工作
} catch (Exception e) {
e.printStackTrace();
return e.getMessage();
}finally {
lock.unlock();//释放锁
}
Is not it simple?
To install redis, you can refer to "Java Cluster: Upgrading from Monolithic Architecture to Cluster Architecture (2) Realizing Session Sharing"
Friends who want to know redisson can read this article:
The strongest distributed lock tool: Redisson
There are too many articles introducing redis and redisson on the Internet, you can find them yourself