当前位置:网站首页>Redis implements distributed locks
Redis implements distributed locks
2022-06-28 07:35:00 【Huangyuewang】
redis The distributed lock core of is in setnx Method , Successfully returns 1, Failure to return 0
Case study : build springboot Integrate redis Implement distributed locks ,100 Scenario where multiple threads produce order numbers at the same time
Ideas :
1, Get the lock , Successfully executed section 2 Step , If it fails, wait for the lock to be acquired successfully
2, Executive business
3, Release the lock
1,pom file
<!-- Integrate SpringBoot-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.6.2</version>
</dependency>
<!-- Integrate redis-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>2.6.3</version>
</dependency>2. establish RedisUtil class
package com.hyw.util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import java.time.Duration;
import java.util.concurrent.TimeUnit;
@Component
public class RedisUtil {
/**
* obtain redis Templates
*/
@Autowired
private StringRedisTemplate redis;
public void setStr(String key, String value){
setStr(key, value, null);
}
/**
* Save string
* @param key
* @param value
* @param timeOut
*/
public void setStr(String key, String value, Long timeOut){
redis.opsForValue().set(key, value);
if(timeOut != null)
redis.expire(key, timeOut, TimeUnit.SECONDS);
}
/**
* SetNx command Every time SetNx Check that key Does it already exist , If it already exists, no operation will be performed . Return to 0 If it doesn't exist, you can add it directly key
* @param key
* @param value
* @param timeOut
* @return
*/
public Integer setnx(String key, String value, Long timeOut){
boolean flag = redis.opsForValue().setIfAbsent(key,value, timeOut, TimeUnit.SECONDS);
return flag?1:0;
}
public Integer setnx(String key, String value){
return setnx(key, value, null);
}
/**
* Delete key
* @param key
*/
public void del(String key){
redis.delete(key);
}
public String getStr(String key){
return redis.opsForValue().get(key);
}
}
3. establish RedisLock class
package com.hyw.lock;
import com.hyw.contans.OrderContans;
import com.hyw.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.UUID;
@Component
public class RedisLock {
@Autowired
private RedisUtil redisUtil;
public String getLock(String lockKey, int notLockTime){
// Calculate the time-out for trying to acquire a lock
Long endTime = System.currentTimeMillis() + notLockTime;
// Exit the loop when it times out
while (System.currentTimeMillis() < endTime){
String lockValue = UUID.randomUUID().toString();
if(redisUtil.setnx(lockKey, lockValue, notLockTime*1l/1000) == OrderContans.lockSuccess){
System.out.println(Thread.currentThread().getName() +" Lock acquired successfully !");
return lockValue;
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
}
/**
* Release the lock
* @param lockKey
* @param lockValue
* @return
*/
public void unlock(String lockKey, String lockValue){
// Judge lockValue Whether the user who has snatched the lock , If yes, delete it , Avoid deleting other people's locks
if(lockValue.equals(redisUtil.getStr(lockKey))){
redisUtil.del(lockKey);
System.out.println(Thread.currentThread().getName() +" Lock release successful !");
}
}
}4, Create constant classes OrderContans
package com.hyw.contans;
public class OrderContans {
/**
* 1 Get lock , 0 Lock not acquired
*/
public static int lockSuccess = 1;
/**
* Order lock key
*/
public static final String LOCK_KEY = "order_lock";
/**
* Set lock timeout 10 second
*/
public static int notLockTime = 10000;
}5,service Cheng Chuang OrderService class , Generate orders
package com.hyw.service;
import com.hyw.contans.OrderContans;
import com.hyw.lock.RedisLock;
import com.hyw.util.OrderUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
@Component
public class OrderService {
@Autowired
private RedisLock redisLock;
public void getOrderNum(){
//1. Get the lock
String lockValue = redisLock.getLock(OrderContans.LOCK_KEY, OrderContans.notLockTime);
if(StringUtils.isEmpty(lockValue)){
System.out.println(" Lock acquisition failed !");
return;
}
System.out.println(" Order number obtained successfully ..."+ OrderUtil.getOrderNumber());
//3. Release the lock
redisLock.unlock(OrderContans.LOCK_KEY, lockValue);
System.out.println();
}
}
6, Create a controller layer OrderController, test result
package com.hyw.controller;
import com.hyw.service.OrderService;
import com.hyw.util.RedisUtil;
@RestController
public class OrderController {
@Autowired
private RedisUtil redisUtil;
@Autowired
private OrderService orderService;
/**
* Get the order number
* @return
*/
@RequestMapping("/getOrderNum")
public String getOrderNum(){
for (int i = 0; i < 100; i++) {
new Thread(new Runnable() {
public void run() {
orderService.getOrderNum();
}
}).start();
}
return "success";
}
}7,springboot Start class
package com.hyw;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import java.text.SimpleDateFormat;
import java.util.Date;
@SpringBootApplication
public class ApplicationMain {
public static void main(String[] args) {
SpringApplication.run(ApplicationMain.class, args);
}
}
Running results :
http://localhost:8888/getOrderNum

边栏推荐
- 剑指Offer||:链表(简单)
- goland IDE和delve调试位于kubernetes集群中的go程序
- 基金的投资交易与结算
- 在idea中,get和set方法爆红可能是没有安装Lombok插件
- Mysql57 zip file installation
- ES6 use of return in arrow function
- Unity-UI-shadow组件
- Can okcc call centers work without computers?
- Introduction and several months' experience of extending the solution thanos of Prometheus
- Leetcode+ 66 - 70 high precision, two sub topics
猜你喜欢

MySQL installation steps - Linux configuration file JDK installation (II)

Design and implementation of spark offline development framework

Unity UI shadow component

Yesterday, I went to a large factory for an interview and asked me to do four arithmetic operations. Fortunately, I am smart enough
面经---测试工程师web端自动化---大厂面试题

kubernetes部署thanos ruler的发送重复告警的一个隐秘的坑

一个小工具可以更快的写爬虫

ACM笔记

剑指Offer||:链表(简单)

HTTP Caching Protocol practice
随机推荐
Huawei cloud computing physical node cna installation tutorial
Top 25 most popular articles on vivo Internet technology in 2021
No suspense about the No. 1 Internet company overtime table
R 语言绘制 动画气泡图
Analyze 5 indicators of NFT project
打新债注册开户靠谱吗?安全吗?
R 语言 Kolmogorov-Smirnov 检验 2 个样本是否遵循相同的分布。
MMR重排(相似度通过编辑距离和重复度计算)
Leetcode+ 51 - 55 retrospective and dynamic planning topics
[thanos source code analysis series]thanos query component source code analysis
SQL statement optimization steps (1)
以动态规划的方式求解最长回文子串
Can okcc call centers work without computers?
Evaluation of inverse Polish expression < difficulty coefficient >
Unity-UI-shadow组件
Application and Optimization Practice of redis in vivo push platform
Modifying MySQL port number under Linux
R 语言 ggmap 可视化集群
Flutter realizes the function of "shake"
PLC -- Notes