Redission implements distributed transactions. Because distributed transactions are implemented, a 9000 port project will be started later. Check the results of Redission by yourself. The blogger was too lazy to take a screenshot of the results of distributed lock implementation

2024/11/2423:31:35 technology 1195

redission and zookeeper respectively implement distributed lock (windows)

1, and Redission implements distributed transaction

1.1 Prerequisite preparation

  • Download nginx (windows version)
  • Download Jmeter (imitation of high concurrency)
  • Download redis (windows version)

1.2 Code

  • pom file
?xml version="1.0" encoding="UTF-8"?project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www. w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"modelVersion4.0.0/modelVersionparentgroupIdorg.springframework.boot/ groupIdartifactIdspring-boot-starter-parent/artifactIdversion2.7.2/versionrelativePath/ !-- lookup parent from repository --/parentgroupIdcn.lanqiao/groupIdartifactIdarcdemo/artifactIdversion0.0.1-SNAPSHOT/versionnamearcdemo/namedescriptionarcdemo/descriptionpropertiesjava.ver sion8/java.version/propertiesdependenciesdependencygroupIdorg.springframework.boot/groupIdartifactIdSpring-boot-starter-data-redis/artifactId/dependencydepe ndencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-web/artifactId/dependencydependencygroupIdorg.springframework.session/groupIdartifactIdspri ng-session-data-redis/artifactId/dependencydependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-test/artifactIdscopetest/scope/dependency!-- redisson --dependencygroupIdorg.redisson/groupIdartifactIdRedisson-spring-boot-starter/artifactIdversion3.17.5/version/dependency/dependenciesbuildpluginsplugingroupIdorg.springframework.boot/groupIdartif actIdspring-boot-maven-plugin/artifactId/plugin/plugins/build/project
  • configuration file
  • Because the distributed transaction is implemented, a 9000 port project will be started later
# Application name spring.application.name=arcdemo# Application service WEB access port server.port=8000# Redis database index (default is 0) spring.redis.database=0# Redis server address spring.redis.host=
27.0.0. 1# Redis server connection port spring.redis.port=6379# Redis server connection password (default is empty) spring.redis.password=# The maximum number of connections in the connection pool (use a negative value to indicate no limit) spring.redis.jedis.pool.max-active=20# The maximum blocking waiting time of the connection pool (use a negative value to indicate no limit) spring.redis.jedis.pool.max -wait=-1# The maximum idle connection in the connection pool spring.redis.jedis.pool.max-idle=10# Minimum idle connection in the connection pool spring.redis.jedis.pool.min-idle=0# Connection timeout (milliseconds) spring.redis.timeout=1000
  • Inject Redisson
package in the main startup class com.example;import org.redisson.Redisson ;import org.redisson.config.Config;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.context.annotation.Bean;import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;@SpringBootApplication@EnableRedisHttpSessionpublic class ArcdemoApplication { public static void main(String[] args) { SpringApplication.run(ArcdemoApplication.class, args);}@Beanpublic Redisson redission() { Config config = new Config();config.useSingleServer().setAddress("redis://localhost:6379").setDatabase(0);return (Redisson) Redisson.create (config);}}
  • controller class
package com.example.controller;import org.apache.curator.framework.CuratorFramework;import org.apache.curator.framework.CuratorFrameworkFactory;import org.apache.curator.framework.recipes.locks.InterProcessMutex;import org.apache.curator. retry.RetryNTimes;import org.redisson.Redisson;import org.redisson.api.RLock;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.data.redis.core.StringRedisTemplate;import org. springframework.http.HttpRequest;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController ;import javax.annotation.Resource;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpSession;import java.util.concurrent.TimeUnit;/** * @Author Devere19 * @Date 2022/8/17 10:41 * @Version 1.0 */ @RestControllerpublic class BiSheController { // private static final String ZK_ADDRESS = "127.0.0.1:2181";//// private static final String ZK_LOCK_PATH = "/zkLock";//// static CuratorFramework client = null;//// static { // //Connect zk// client = CuratorFrameworkFactory.newClient(ZK_ADDRESS,// new RetryNTimes(10, 5000));// client.start();// }// Distributed lock@Autowiredprivate Redisson redisson;@Resourceprivate StringRedisTemplate StringRedisTemplate;@GetMapping("/login")public String login(String username, HttpSession session, HttpServletRequest request) { session.setAttribute( "username", username);return username + ",port" + request.getLocalPort();}@GetMapping("/getUser")public String getUser(HttpSession session, HttpServletRequest request) { String username = (String) session.getAttribute("username");return session.getId() + ", " + username + ",port" + request.getLocalPort();}@PostMapping("/checkTeacher")public String checkteacher(String teacherName) { // SpringBoot operation RedisString lockKey = "lockKey";RLock redissonLock = null;String num = "";try { redissonLock = redisson.getLock("lockKey");//Lock redissonLock.tryLock(30 , TimeUnit.SECONDS);//Timeout time: every 10 seconds (1/3) num = stringRedisTemplate.opsForValue().get(teacherName);int n = Integer.parseInt(num);if (n 0) { n = n - 1;stringRedisTemplate.opsForValue().set("lkz", n + "") ;//Select teachers normally System.out.println("Current quota:" + n);} else { return "Quota is full";}} catch (InterruptedException e) { e.printStackTrace();} finally { redissonLock.unlock();//Release the lock}return num;}// @PostMapping("/checkTeacher")// public String checkteacher(String teacherName) { / / InterProcessMutex lock = new InterProcessMutex(client, ZK_LOCK_PATH);// String num = "";// try { // if (lock.acquire(6000, TimeUnit.SECONDS)) { // // System.out.println("Get the lock"); // //Business logic // num = stringRedisTemplate.opsForValue().get (teacherName);// int n = Integer.parseInt(num);// if (n 0) { // n = n - 1;// stringRedisTemplate.opsForValue().set("lkz", n + "");// //Normal selection of teachers // System.out.println("Current quota: " + n);// } else { // return "The quota is full";// }// // System.out.println("The task is completed, it is time to release the lock");// }// } catch (Exception e) { // System.out.println("Business Exception");// e.printStackTrace();// }finally { // try { // lock.release();// } catch (Exception e) { // System. out.println("Lock release exception");// e.printStackTrace();// }// }// return num;// }}
  • redis needs the corresponding key
set lkz 6

Redission implements distributed transactions. Because distributed transactions are implemented, a 9000 port project will be started later. Check the results of Redission by yourself. The blogger was too lazy to take a screenshot of the results of distributed lock implementation  - DayDayNews

1.3 Start the project

  • The first step: start redis, and assign the value
  • to lkz The second step: start nginx, nginx needs to be configured to point to the local 8000 and 9000 ports
upstream testdev{server 127.0.0.1:8000 weight=1;server 127.0.0.1:9000 weight=1; }server {listen 80;server_namelocalhost;#charset koi8-r;#access_loglogs/host.access.logmain;location / {root html;indexindex.html index.htm;proxy_pass http:// testdev;proxy_redirect default;}
  • Step 3: Start port 8000 in the idea, and then modify the configuration file port, and then start port 9000

Redission implements distributed transactions. Because distributed transactions are implemented, a 9000 port project will be started later. Check the results of Redission by yourself. The blogger was too lazy to take a screenshot of the results of distributed lock implementation  - DayDayNews

Click this, and then Then modify 9000 to start 8000 and 9000 ports at the same time

  • Step 3: Start Jmeter and send a request

Redission implements distributed transactions. Because distributed transactions are implemented, a 9000 port project will be started later. Check the results of Redission by yourself. The blogger was too lazy to take a screenshot of the results of distributed lock implementation  - DayDayNews

Redission implements distributed transactions. Because distributed transactions are implemented, a 9000 port project will be started later. Check the results of Redission by yourself. The blogger was too lazy to take a screenshot of the results of distributed lock implementation  - DayDayNews

1.4 The results of

Redission can be viewed by yourself. The blogger was lazy and took a screenshot of the results of implementing distributed locks in zookeeper below.

2, Zookeeper implements distributed lock

2.1 Prerequisite preparation:

  • Download nginx (windows version)
  • Download Jmeter (imitation of high concurrency)
  • Download redis (windows version)
  • Download zookeeper (windows version) and ZooInspector (visualization tool, you don’t need to download)

2.2 Code

  • pom file
?xml version="1.0" encoding="UTF-8"?project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www. w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"modelVersion4.0.0/modelVersionparentgroupIdorg.springframework.boot/ groupIdartifactIdspring-boot-starter-parent/artifactIdversion2.7.2/versionrelativePath/ !-- lookup parent from repository --/parentgroupIdcn.lanqiao/groupIdartifactIdarcdemo/artifactIdversion0.0.1-SNAPSHOT/versionnamearcdemo/namedescriptionarcdemo/descriptionpropertiesjava.version8 /java.version/propertiesdependenciesdependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-data-redis/artifactId/dependencydependencygrou pIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-web/artifactId/dependencydependencygroupIdorg.springframework.session/groupIdartifactIdspring-se ssion-data-redis/artifactId/dependencydependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-test/artifactIdscopetest/scope/dependency!-- redisson --dependencygroupIdorg.redisson/groupIdartifactIdredisson-spring-boot-starter/artifactIdversion3.17.5/version/dependency! --zookeeper and curator --dependencygroupIdorg.apache.zookeeper/groupIdartifactIdzoo keeper/artifactIdversion3.5.7/version/dependencydependencygroupIdorg.apache.curator/groupIdartifactIdcurator-framework/artifactIdversion4.3.0/version/dependencydependencygroupIdorg.apache.curator/group IdartifactIdcurator-recipes/artifactIdversion4.3.0/version/dependencydependencygroupIdorg.apache.curator/groupIdartifactIdcurator-client/artifactIdversion4.3.0/version/dependency/dependenciesbuildplug insplugingroupIdorg.springframework.boot/groupIdartifactIdspring-boot-maven-plugin/artifactId/plugin/plugins/build/project
  • controller
package com.example.controller;import org.apache.curator.framework.CuratorFramework;import org.apache.curator.framework.CuratorFrameworkFactory;import org.apache.curator.framework.recipes.locks.InterProcessMutex;import org.apache.curator. retry.RetryNTimes;import org.redisson.Redisson;import org.redisson.api.RLock;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.data.redis.core.StringRedisTemplate;import org. springframework.http.HttpRequest;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController ;import javax.annotation.Resource;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpSession;import java.util.concurrent.TimeUnit;/** * @Author Devere19 * @Date 2022/8/17 10:41 * @Version 1.0 */ @RestControllerpublic class BiSheController { private static final String ZK_ADDRESS = "127.0.0.1:2181";private static final String ZK_LOCK_PATH = "/zkLock";static CuratorFramework client = null;static { //Connect zkclient = CuratorFrameworkFactory.newClient(ZK_ADDRESS,new RetryNTimes(10, 5000));client.start ();}// Distributed lock// @Autowired// private Redisson redisson;@Resourceprivate StringRedisTemplate stringRedisTemplate;@GetMapping("/login")public String login(String username, HttpSession session, HttpServletRequest request) { session.setAttribute("username", username);return username + ",port" + request .getLocalPort();}@GetMapping("/getUser")public String getUser(HttpSession session, HttpServletRequest request) { String username = (String) session.getAttribute("username");return session.getId() + "," + username + ",port" + request.getLocalPort();}/ / @PostMapping("/checkTeacher")// public String checkteacher(String teacherName) { // // SpringBoot operates Redis// String lockKey = "lockKey";// RLock redissonLock = null;// String num = "";// try { // redissonLock = redisson.getLock("lockKey");//lock// redissonLock.tryLock(30, TimeUnit.SECONDS);//Timeout time: every 10 seconds (1/3)//num = stringRedisTemplate.opsForValue().get(teacherName);// int n = Integer.parseInt(num);//// if (n 0) { // n = n - 1;// stringRedisTemplate.opsForValue().set ("lkz", n + "");// //Normal selection of teachers// System.out.println("Current quota: " + n);// } else { // return "Quota is full";// }// } catch (InterruptedException e) { // e.printStackTrace();// } finally { // redissonLock.unlock();//release the lock/ / }// return num;// }@PostMapping("/checkTeacher")public String checkteacher(String teacherName) { InterProcessMutex lock = new InterProcessMutex(client, ZK_LOCK_PATH);String num = "";try { if (lock.acquire(6000, TimeUnit.SECONDS)) { // System.out.println("Get the lock");//Business logic num = stringRedisTemplate.opsForValue().get(teacherName);int n = Integer.parseInt(num);if (n 0) { n = n - 1;stringRedisTemplate.opsForValue().set("lkz", n + "");//Normal selection of teachers System.out.println("Current quota: " + n);} else { return " The quota is full";}// System.out.println("The task is completed, it is time to release the lock");}} catch (Exception e) { System.out.println("Business Exception");e.printStackTrace();}finally { try { lock.release();} catch (Exception e) { System.out.println("Lock Release Exception");e .printStackTrace();}}return num;}}

2.3 Start the project

  • The first step: start redis, and assign the value
  • to lkz The second step: start nginx, nginx needs to be configured to point to the local 8000 and 9000 ports
upstream testdev{server 127.0.0.1:8000 weight=1;server 127.0.0.1:9000 weight=1; }server {listen 80;server_namelocalhost;#charset koi8-r;#access_loglogs/host.access.logmain;location / {root html;indexindex.html index.htm;proxy_pass http:// testdev;proxy_redirect default;}
  • Step 3: Start port 8000 in the idea, and then modify the configuration file port, and then start port 9000

Redission implements distributed transactions. Because distributed transactions are implemented, a 9000 port project will be started later. Check the results of Redission by yourself. The blogger was too lazy to take a screenshot of the results of distributed lock implementation  - DayDayNews

Click this, and then modify 9000 to start 8000 and 9000 ports html at the same time 2

  • Step 3: Start zookeeper and start the ZooInspector visualization tool
  • Step 4: Start Jmeter and send a request

Redission implements distributed transactions. Because distributed transactions are implemented, a 9000 port project will be started later. Check the results of Redission by yourself. The blogger was too lazy to take a screenshot of the results of distributed lock implementation  - DayDayNews

Redission implements distributed transactions. Because distributed transactions are implemented, a 9000 port project will be started later. Check the results of Redission by yourself. The blogger was too lazy to take a screenshot of the results of distributed lock implementation  - DayDayNews

2.4 Result

Redission implements distributed transactions. Because distributed transactions are implemented, a 9000 port project will be started later. Check the results of Redission by yourself. The blogger was too lazy to take a screenshot of the results of distributed lock implementation  - DayDayNews

Redission implements distributed transactions. Because distributed transactions are implemented, a 9000 port project will be started later. Check the results of Redission by yourself. The blogger was too lazy to take a screenshot of the results of distributed lock implementation  - DayDayNews

Seeing the output of the console, it can be seen that the distributed lock works, and you can watch ZooInspector to view

Redission implements distributed transactions. Because distributed transactions are implemented, a 9000 port project will be started later. Check the results of Redission by yourself. The blogger was too lazy to take a screenshot of the results of distributed lock implementation  - DayDayNews

Because an ordered temporary lock is used here, the lock is deleted after the request is sent.It must be refreshed at the moment the request is initiated to see the sorted locks.

3, case source code address

https://github.com/Guoleyuan/arcdemo

redission and zookeeper respectively implement distributed lock (windows)

1, and Redission implements distributed transaction

1.1 Prerequisite preparation

  • Download nginx (windows version)
  • Download Jmeter (imitation of high concurrency)
  • Download redis (windows version)

1.2 Code

  • pom file
?xml version="1.0" encoding="UTF-8"?project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www. w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"modelVersion4.0.0/modelVersionparentgroupIdorg.springframework.boot/ groupIdartifactIdspring-boot-starter-parent/artifactIdversion2.7.2/versionrelativePath/ !-- lookup parent from repository --/parentgroupIdcn.lanqiao/groupIdartifactIdarcdemo/artifactIdversion0.0.1-SNAPSHOT/versionnamearcdemo/namedescriptionarcdemo/descriptionpropertiesjava.ver sion8/java.version/propertiesdependenciesdependencygroupIdorg.springframework.boot/groupIdartifactIdSpring-boot-starter-data-redis/artifactId/dependencydepe ndencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-web/artifactId/dependencydependencygroupIdorg.springframework.session/groupIdartifactIdspri ng-session-data-redis/artifactId/dependencydependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-test/artifactIdscopetest/scope/dependency!-- redisson --dependencygroupIdorg.redisson/groupIdartifactIdRedisson-spring-boot-starter/artifactIdversion3.17.5/version/dependency/dependenciesbuildpluginsplugingroupIdorg.springframework.boot/groupIdartif actIdspring-boot-maven-plugin/artifactId/plugin/plugins/build/project
  • configuration file
  • Because the distributed transaction is implemented, a 9000 port project will be started later
# Application name spring.application.name=arcdemo# Application service WEB access port server.port=8000# Redis database index (default is 0) spring.redis.database=0# Redis server address spring.redis.host=
27.0.0. 1# Redis server connection port spring.redis.port=6379# Redis server connection password (default is empty) spring.redis.password=# The maximum number of connections in the connection pool (use a negative value to indicate no limit) spring.redis.jedis.pool.max-active=20# The maximum blocking waiting time of the connection pool (use a negative value to indicate no limit) spring.redis.jedis.pool.max -wait=-1# The maximum idle connection in the connection pool spring.redis.jedis.pool.max-idle=10# Minimum idle connection in the connection pool spring.redis.jedis.pool.min-idle=0# Connection timeout (milliseconds) spring.redis.timeout=1000
  • Inject Redisson
package in the main startup class com.example;import org.redisson.Redisson ;import org.redisson.config.Config;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.context.annotation.Bean;import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;@SpringBootApplication@EnableRedisHttpSessionpublic class ArcdemoApplication { public static void main(String[] args) { SpringApplication.run(ArcdemoApplication.class, args);}@Beanpublic Redisson redission() { Config config = new Config();config.useSingleServer().setAddress("redis://localhost:6379").setDatabase(0);return (Redisson) Redisson.create (config);}}
  • controller class
package com.example.controller;import org.apache.curator.framework.CuratorFramework;import org.apache.curator.framework.CuratorFrameworkFactory;import org.apache.curator.framework.recipes.locks.InterProcessMutex;import org.apache.curator. retry.RetryNTimes;import org.redisson.Redisson;import org.redisson.api.RLock;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.data.redis.core.StringRedisTemplate;import org. springframework.http.HttpRequest;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController ;import javax.annotation.Resource;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpSession;import java.util.concurrent.TimeUnit;/** * @Author Devere19 * @Date 2022/8/17 10:41 * @Version 1.0 */ @RestControllerpublic class BiSheController { // private static final String ZK_ADDRESS = "127.0.0.1:2181";//// private static final String ZK_LOCK_PATH = "/zkLock";//// static CuratorFramework client = null;//// static { // //Connect zk// client = CuratorFrameworkFactory.newClient(ZK_ADDRESS,// new RetryNTimes(10, 5000));// client.start();// }// Distributed lock@Autowiredprivate Redisson redisson;@Resourceprivate StringRedisTemplate StringRedisTemplate;@GetMapping("/login")public String login(String username, HttpSession session, HttpServletRequest request) { session.setAttribute( "username", username);return username + ",port" + request.getLocalPort();}@GetMapping("/getUser")public String getUser(HttpSession session, HttpServletRequest request) { String username = (String) session.getAttribute("username");return session.getId() + ", " + username + ",port" + request.getLocalPort();}@PostMapping("/checkTeacher")public String checkteacher(String teacherName) { // SpringBoot operation RedisString lockKey = "lockKey";RLock redissonLock = null;String num = "";try { redissonLock = redisson.getLock("lockKey");//Lock redissonLock.tryLock(30 , TimeUnit.SECONDS);//Timeout time: every 10 seconds (1/3) num = stringRedisTemplate.opsForValue().get(teacherName);int n = Integer.parseInt(num);if (n 0) { n = n - 1;stringRedisTemplate.opsForValue().set("lkz", n + "") ;//Select teachers normally System.out.println("Current quota:" + n);} else { return "Quota is full";}} catch (InterruptedException e) { e.printStackTrace();} finally { redissonLock.unlock();//Release the lock}return num;}// @PostMapping("/checkTeacher")// public String checkteacher(String teacherName) { / / InterProcessMutex lock = new InterProcessMutex(client, ZK_LOCK_PATH);// String num = "";// try { // if (lock.acquire(6000, TimeUnit.SECONDS)) { // // System.out.println("Get the lock"); // //Business logic // num = stringRedisTemplate.opsForValue().get (teacherName);// int n = Integer.parseInt(num);// if (n 0) { // n = n - 1;// stringRedisTemplate.opsForValue().set("lkz", n + "");// //Normal selection of teachers // System.out.println("Current quota: " + n);// } else { // return "The quota is full";// }// // System.out.println("The task is completed, it is time to release the lock");// }// } catch (Exception e) { // System.out.println("Business Exception");// e.printStackTrace();// }finally { // try { // lock.release();// } catch (Exception e) { // System. out.println("Lock release exception");// e.printStackTrace();// }// }// return num;// }}
  • redis needs the corresponding key
set lkz 6

Redission implements distributed transactions. Because distributed transactions are implemented, a 9000 port project will be started later. Check the results of Redission by yourself. The blogger was too lazy to take a screenshot of the results of distributed lock implementation  - DayDayNews

1.3 Start the project

  • The first step: start redis, and assign the value
  • to lkz The second step: start nginx, nginx needs to be configured to point to the local 8000 and 9000 ports
upstream testdev{server 127.0.0.1:8000 weight=1;server 127.0.0.1:9000 weight=1; }server {listen 80;server_namelocalhost;#charset koi8-r;#access_loglogs/host.access.logmain;location / {root html;indexindex.html index.htm;proxy_pass http:// testdev;proxy_redirect default;}
  • Step 3: Start port 8000 in the idea, and then modify the configuration file port, and then start port 9000

Redission implements distributed transactions. Because distributed transactions are implemented, a 9000 port project will be started later. Check the results of Redission by yourself. The blogger was too lazy to take a screenshot of the results of distributed lock implementation  - DayDayNews

Click this, and then Then modify 9000 to start 8000 and 9000 ports at the same time

  • Step 3: Start Jmeter and send a request

Redission implements distributed transactions. Because distributed transactions are implemented, a 9000 port project will be started later. Check the results of Redission by yourself. The blogger was too lazy to take a screenshot of the results of distributed lock implementation  - DayDayNews

Redission implements distributed transactions. Because distributed transactions are implemented, a 9000 port project will be started later. Check the results of Redission by yourself. The blogger was too lazy to take a screenshot of the results of distributed lock implementation  - DayDayNews

1.4 The results of

Redission can be viewed by yourself. The blogger was lazy and took a screenshot of the results of implementing distributed locks in zookeeper below.

2, Zookeeper implements distributed lock

2.1 Prerequisite preparation:

  • Download nginx (windows version)
  • Download Jmeter (imitation of high concurrency)
  • Download redis (windows version)
  • Download zookeeper (windows version) and ZooInspector (visualization tool, you don’t need to download)

2.2 Code

  • pom file
?xml version="1.0" encoding="UTF-8"?project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www. w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"modelVersion4.0.0/modelVersionparentgroupIdorg.springframework.boot/ groupIdartifactIdspring-boot-starter-parent/artifactIdversion2.7.2/versionrelativePath/ !-- lookup parent from repository --/parentgroupIdcn.lanqiao/groupIdartifactIdarcdemo/artifactIdversion0.0.1-SNAPSHOT/versionnamearcdemo/namedescriptionarcdemo/descriptionpropertiesjava.version8 /java.version/propertiesdependenciesdependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-data-redis/artifactId/dependencydependencygrou pIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-web/artifactId/dependencydependencygroupIdorg.springframework.session/groupIdartifactIdspring-se ssion-data-redis/artifactId/dependencydependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-test/artifactIdscopetest/scope/dependency!-- redisson --dependencygroupIdorg.redisson/groupIdartifactIdredisson-spring-boot-starter/artifactIdversion3.17.5/version/dependency! --zookeeper and curator --dependencygroupIdorg.apache.zookeeper/groupIdartifactIdzoo keeper/artifactIdversion3.5.7/version/dependencydependencygroupIdorg.apache.curator/groupIdartifactIdcurator-framework/artifactIdversion4.3.0/version/dependencydependencygroupIdorg.apache.curator/group IdartifactIdcurator-recipes/artifactIdversion4.3.0/version/dependencydependencygroupIdorg.apache.curator/groupIdartifactIdcurator-client/artifactIdversion4.3.0/version/dependency/dependenciesbuildplug insplugingroupIdorg.springframework.boot/groupIdartifactIdspring-boot-maven-plugin/artifactId/plugin/plugins/build/project
  • controller
package com.example.controller;import org.apache.curator.framework.CuratorFramework;import org.apache.curator.framework.CuratorFrameworkFactory;import org.apache.curator.framework.recipes.locks.InterProcessMutex;import org.apache.curator. retry.RetryNTimes;import org.redisson.Redisson;import org.redisson.api.RLock;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.data.redis.core.StringRedisTemplate;import org. springframework.http.HttpRequest;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController ;import javax.annotation.Resource;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpSession;import java.util.concurrent.TimeUnit;/** * @Author Devere19 * @Date 2022/8/17 10:41 * @Version 1.0 */ @RestControllerpublic class BiSheController { private static final String ZK_ADDRESS = "127.0.0.1:2181";private static final String ZK_LOCK_PATH = "/zkLock";static CuratorFramework client = null;static { //Connect zkclient = CuratorFrameworkFactory.newClient(ZK_ADDRESS,new RetryNTimes(10, 5000));client.start ();}// Distributed lock// @Autowired// private Redisson redisson;@Resourceprivate StringRedisTemplate stringRedisTemplate;@GetMapping("/login")public String login(String username, HttpSession session, HttpServletRequest request) { session.setAttribute("username", username);return username + ",port" + request .getLocalPort();}@GetMapping("/getUser")public String getUser(HttpSession session, HttpServletRequest request) { String username = (String) session.getAttribute("username");return session.getId() + "," + username + ",port" + request.getLocalPort();}/ / @PostMapping("/checkTeacher")// public String checkteacher(String teacherName) { // // SpringBoot operates Redis// String lockKey = "lockKey";// RLock redissonLock = null;// String num = "";// try { // redissonLock = redisson.getLock("lockKey");//lock// redissonLock.tryLock(30, TimeUnit.SECONDS);//Timeout time: every 10 seconds (1/3)//num = stringRedisTemplate.opsForValue().get(teacherName);// int n = Integer.parseInt(num);//// if (n 0) { // n = n - 1;// stringRedisTemplate.opsForValue().set ("lkz", n + "");// //Normal selection of teachers// System.out.println("Current quota: " + n);// } else { // return "Quota is full";// }// } catch (InterruptedException e) { // e.printStackTrace();// } finally { // redissonLock.unlock();//release the lock/ / }// return num;// }@PostMapping("/checkTeacher")public String checkteacher(String teacherName) { InterProcessMutex lock = new InterProcessMutex(client, ZK_LOCK_PATH);String num = "";try { if (lock.acquire(6000, TimeUnit.SECONDS)) { // System.out.println("Get the lock");//Business logic num = stringRedisTemplate.opsForValue().get(teacherName);int n = Integer.parseInt(num);if (n 0) { n = n - 1;stringRedisTemplate.opsForValue().set("lkz", n + "");//Normal selection of teachers System.out.println("Current quota: " + n);} else { return " The quota is full";}// System.out.println("The task is completed, it is time to release the lock");}} catch (Exception e) { System.out.println("Business Exception");e.printStackTrace();}finally { try { lock.release();} catch (Exception e) { System.out.println("Lock Release Exception");e .printStackTrace();}}return num;}}

2.3 Start the project

  • The first step: start redis, and assign the value
  • to lkz The second step: start nginx, nginx needs to be configured to point to the local 8000 and 9000 ports
upstream testdev{server 127.0.0.1:8000 weight=1;server 127.0.0.1:9000 weight=1; }server {listen 80;server_namelocalhost;#charset koi8-r;#access_loglogs/host.access.logmain;location / {root html;indexindex.html index.htm;proxy_pass http:// testdev;proxy_redirect default;}
  • Step 3: Start port 8000 in the idea, and then modify the configuration file port, and then start port 9000

Redission implements distributed transactions. Because distributed transactions are implemented, a 9000 port project will be started later. Check the results of Redission by yourself. The blogger was too lazy to take a screenshot of the results of distributed lock implementation  - DayDayNews

Click this, and then modify 9000 to start 8000 and 9000 ports html at the same time 2

  • Step 3: Start zookeeper and start the ZooInspector visualization tool
  • Step 4: Start Jmeter and send a request

Redission implements distributed transactions. Because distributed transactions are implemented, a 9000 port project will be started later. Check the results of Redission by yourself. The blogger was too lazy to take a screenshot of the results of distributed lock implementation  - DayDayNews

Redission implements distributed transactions. Because distributed transactions are implemented, a 9000 port project will be started later. Check the results of Redission by yourself. The blogger was too lazy to take a screenshot of the results of distributed lock implementation  - DayDayNews

2.4 Result

Redission implements distributed transactions. Because distributed transactions are implemented, a 9000 port project will be started later. Check the results of Redission by yourself. The blogger was too lazy to take a screenshot of the results of distributed lock implementation  - DayDayNews

Redission implements distributed transactions. Because distributed transactions are implemented, a 9000 port project will be started later. Check the results of Redission by yourself. The blogger was too lazy to take a screenshot of the results of distributed lock implementation  - DayDayNews

Seeing the output of the console, it can be seen that the distributed lock works, and you can watch ZooInspector to view

Redission implements distributed transactions. Because distributed transactions are implemented, a 9000 port project will be started later. Check the results of Redission by yourself. The blogger was too lazy to take a screenshot of the results of distributed lock implementation  - DayDayNews

Because an ordered temporary lock is used here, the lock is deleted after the request is sent.It must be refreshed at the moment the request is initiated to see the sorted locks.

3, case source code address

https://github.com/Guoleyuan/arcdemo

It must be refreshed at the moment the request is initiated to see the sorted locks.

3, case source code address

https://github.com/Guoleyuan/arcdemo

technology Category Latest News