当前位置:网站首页>[development of large e-commerce projects] cache distributed lock redisson concise & integration lock redisson resolve deadlock read / write lock lock lock semaphore-44
[development of large e-commerce projects] cache distributed lock redisson concise & integration lock redisson resolve deadlock read / write lock lock lock semaphore-44
2022-07-18 22:55:00 【Random stone light】
One :Redisson—— Complete the distributed lock
1. brief introduction
Redisson It's set up in Redis Based on a Java In memory data grid (In-Memory Data Grid). to the full I've made good use of it Redis Key value database provides a series of advantages , be based on Java Common interfaces in utility kits , For users It provides a series of common tool classes with distributed characteristics . This makes the original worker as a coordinator of single machine multithreaded concurrent programs The package obtains the ability to coordinate distributed multi machine multi-threaded concurrent systems , It greatly reduces the cost of designing and developing large-scale distributed systems The difficulty of the system . At the same time, combined with the characteristics of distributed services , It further simplifies the interaction between programs in a distributed environment Cooperation .
Official documents :https://github.com/redisson/redisson/wiki/%E7%9B%AE%E5%BD%95
2. Import redisson rely on —— Integrate redisson As a framework for distributed locks
<!-- Use redisson As a distributed lock , Distributed objects and other functional frameworks --> <dependency> <groupId>org.redisson</groupId> <artifactId>redisson</artifactId> <version>3.12.0</version> </dependency>
3. To configure redisson
1) newly build MyRedissonConfig file , To configure redisson
package com.sysg.gulimail.product.config;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.io.IOException;
@Configuration
public class MyRedissonConfig {
/** * All right redisson It's all used through RedissonClient object * @return * @throws IOException */
@Bean(destroyMethod = "shutdown")
public RedissonClient redisson() throws IOException {
//1. Create a configuration
Config config = new Config();
config.useSingleServer().setAddress(redis://127.0.0.1:6379");
//2. according to config object , Create RedissonClient Example
RedissonClient redissonClient = Redisson.create(config);
return redissonClient;
}
}
- Create a configuration
Config config = new Config(); - Use single cluster mode
config.useSingleServer().setAddress(127.0.0.1:6379"); - according to config object , Create RedissonClient Example
RedissonClient redissonClient = Redisson.create(config); redis://A secure connection
Two : Reentrant lock —— Avoid deadlock
Reentrant lock : be based on redis Of redisson Distributed . Realized java Object's lock Interface .
1. Code implementation
@ResponseBody
@GetMapping("/hello")
public String hello(){
//1. Get a lock , As long as the lock has the same name , It's a lock
RLock lock = redisson.getLock("my-lock");
//2. Lock
lock.lock();// Block wait , Keep waiting , Until I get the lock , Will execute down
try {
System.out.println(" Locking success , Execute business with code .."+Thread.currentThread().getId());
Thread.sleep(30000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
//3. Unlock
System.out.println(" Release the lock ..."+Thread.currentThread().getId());
lock.unlock();
}
return "hello";
}
- Get a lock :
RLock lock = redisson.getLock("my-lock");As long as the lock has the same name , It's a lock - Lock :
lock.lock();Block wait , Keep waiting , Until I get the lock , Will execute down - Unlock :
lock.unlock();
redisson advantage :—— The watchdog mechanism
1. Solved the automatic renewal of locks , If the business is too long , A new one will be automatically added during operation 30s. Don't worry that the lock will expire and be automatically deleted .
2. Lock the business as long as the operation is completed , No automatic renewal , Even if you don't manually unlock , Default 30s It will unlock automatically in the future .
2. Use lock Method plus timeout
lock.lock(10, TimeUnit.SECONDS);
Thread.sleep(30000);// Business execution time
- After the lock arrived , No automatic renewal
- The automatic unlocking time must be greater than the execution time of the business
Conclusion :
1. If a timeout is specified , Just send it to redis Execute the script , Hold the lock , Default timeout , Is the designated time .
2. If no timeout is specified , We just use 【LockWatchdogTimeout watchdog 】 Default time for .
3. As long as the lock is successful , Will start the scheduled task , The expiration time will be reset , The new time is the default time of the watchdog .
4. As long as the business is not completed , Every third of the watchdog time , Automatic renewal .
5. It is recommended to lock at a specified time , Try to make the time longer . If it is too long , It means that there is a problem with the business code .
3、 ... and : Read-write lock (ReadWriteLock)
Read-write lock : Distributed re entrant read and write locks allow multiple read locks and one write lock to be locked at the same time . Read locks and write locks exist in pairs . The write lock controls the read lock , As long as the write lock exists , Read the lock and wait
1. Test the read-write lock
@GetMapping("/write")
@ResponseBody
public String writeValue(){
RReadWriteLock readWriteLock = redisson.getReadWriteLock("rw-lock");
RLock writeLock = readWriteLock.writeLock();
String s = "";
try {
//1. Change data and add write lock , Read data and add read lock
writeLock.lock();
s = UUID.randomUUID().toString();
Thread.sleep(30000);
redisTemplate.opsForValue().set("writeValue",s);
} catch (Exception e) {
e.printStackTrace();
} finally {
writeLock.unlock();
}
return s;
}
@GetMapping("/read")
@ResponseBody
public String readValue(){
RReadWriteLock readWriteLock = redisson.getReadWriteLock("rw-lock");
RLock readLock = readWriteLock.readLock();
String readValue = "";
readLock.lock();
try {
readLock.lock();
readValue = redisTemplate.opsForValue().get("writeValue");
} catch (Exception e) {
e.printStackTrace();
} finally {
readLock.unlock();
}
return readValue;
}
2. Read write lock features
Read the lock : Read lock is a shared lock , Everyone can use
Write lock : Writing lock is exclusive lock ( The mutex , Exclusive lock ), Only one can exist at a time
1) Write lock + Read the lock
- 1. Change data and add write lock , Read data and add read lock
- 2. Ensure that the latest data can be read , During revision , Writing lock is exclusive lock ( The mutex , Exclusive lock ), Only one can exist at a time . Read lock is a shared lock , Everyone can use
- 3. The lock is not released , Read lock must wait
2) Read the lock + Read the lock
- It's like no lock , Concurrent reading , Only in redis Record all current read locks in , And lock successfully at the same time
3) Write lock + Write lock
- Blocking mode
4) Read the lock + Write lock
- There's a read lock , Write lock also needs to wait . As long as there is writing , Must wait .
Four : atresia —— Wait for all other threads to finish executing before releasing
give an example : Have a holiday , To lock the door . You can't lock the door until all the students have left .
1. Code implementation
/** * Have a holiday , To lock the door . You can't lock the door until all the students have left . * @return * @throws InterruptedException */
@GetMapping("/lockDoor")
@ResponseBody
public String lockDoor() throws InterruptedException{
RCountDownLatch door = redisson.getCountDownLatch("door");
door.trySetCount(5);
door.await(); // Wait until the locking is complete
return " be on holiday ...";
}
@GetMapping("/gogogo/{id}")
@ResponseBody
public String gogogo(@PathVariable("id") Long id){
RCountDownLatch door = redisson.getCountDownLatch("door");
door.countDown();// Count minus one
return id + " Everyone in the class left ";
}
5、 ... and : Distributed semaphores (Semaphore)—— Used to realize distributed current limiting
give an example : Garage parking , Three parking spaces , One car will occupy a parking space , Take one car and release one parking space , When the car , See if the parking space is enough
1. Code implementation
/** * Garage parking , Three parking spaces , One car will occupy a parking space , Take one car and release one parking space , When the car , See if the parking space is enough * @return */
@GetMapping("/park")
@ResponseBody
public String park() throws InterruptedException {
RSemaphore park = redisson.getSemaphore("name");
// It is equivalent to occupying a parking space
//park.acquire();// Blocking method , Return only after success , Otherwise, always call
boolean b = park.tryAcquire();
if (b) {
// Execute complex business
return "ok";
} else {
return " Too much flow , Please wait ";
}
}
@GetMapping("/go")
@ResponseBody
public String go() throws InterruptedException {
RSemaphore park = redisson.getSemaphore("name");
// It is equivalent to releasing a parking space
park.release();
return "ok";
}
- It can be used to implement distributed current limiting Services , Get the semaphore and you can access , Wait until you get it .
- tryAcquire Stop if you can , Leave if you can't stop , Try to get
- acquire Will be waiting , Wait until
边栏推荐
- 训练过程中出现loss为nan的问题
- NASA首次拍到宇宙大爆炸后一瞬间的清晰照片
- Leetcode 49. Alphabetic heterotopic word grouping
- 三维点云课程(二)——最邻近问题
- 416.分割等和子集·背包问题·动态规划
- 创建型模式之享元模式
- 2022.7.14-----leetcode. seven hundred and forty-five
- [basic service] [database] MySQL master-slave replication deployment and configuration
- Listen to drag and drop events. You can't get the uploaded file content by dragging for the first time, and you can get the uploaded file content normally after the second time
- 三维点云课程(三)——聚类
猜你喜欢

Peking University and Microsoft jointly proposed a super time series representation learning framework, which significantly improved the effect of multiple time series tasks

sklearn线性回归拟合一次项函数

时序事件数据怎么处理?【慕尼黑工业大学博士论文】神经时序点过程(NTPP): 连续时间事件数据建模

After reading this article, I will teach you to play with vulnhub, the penetration test target machine -- evilbox one

多租户SaaS的数据库设计模式
![Remove the k-bit number [greedy thought & monotonic stack implementation]](/img/10/cdd14ca5f5887ecaa3abe4b1acc6c0.png)
Remove the k-bit number [greedy thought & monotonic stack implementation]

记一次蚂蚁金服四面遭虐,面试水太深,过河的渡船你造好了吗?

关于产品 | 要怎么进行产品规划?

DeepMind最新114页报告《多智能体强化学习中的新兴易货贸易行为》

The best way to practice Animation: cover transition
随机推荐
Gym报错 The observation returned by the `reset()` method is not contained with the .......
Detailed explanation of bean's life cycle
The problem of loss as Nan occurred during the training
NASA took the first clear picture of the moment after the big bang
浅拷贝与深拷贝
leetcode--49字母异位词分组
Solution to Chinese garbled code in response results of burpsuite tool
数据受限条件下的多模态处理技术综述
原装rexroth比例阀4WRBA10W64-2X/G24N9Z4/M
10 minutes to customize the pedestrian analysis system, detection and tracking, behavior recognition, human attributes all in one
2022.7.15-----leetcode. five hundred and fifty-eight
Honghu Wanlian Zhiyuan development board is officially integrated into the openharmony backbone
训练过程中出现loss为nan的问题
Web development from entry to proficiency I (detailed)
Program analysis and Optimization - 11 multi branch analysis
(board) acwing841 String hash
封装、获取系统用户信息、角色及权限控制
Marvell88Q5192 switch调试记录(BSTA1000B平台)
[advanced C language] ⑨ dynamic memory allocation knowledge summary is super detailed
Which securities company has a low handling fee for opening an account, and which stock is safe to open an account