Redission和Zookeeper分別實現分布式鎖

2022年08月20日10:49:04 科技 1195

redission和zookeeper分別實現分布式鎖(windows)

1、Redission實現分布式事務

1.1 前提準備

  • 下載好nginx(windows版本)
  • 下載好Jmeter(模仿高並發)
  • 下載好redis(windows版)

1.2 代碼

  • pom文件
<?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">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <groupId>cn.lanqiao</groupId>
    <artifactId>arcdemo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>arcdemo</name>
    <description>arcdemo</description>


    <properties>
        <java.version>8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>Spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session-data-redis</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- redisson -->
        <dependency>
            <groupId>org.redisson</groupId>
            <artifactId>Redisson-spring-boot-starter</artifactId>
            <version>3.17.5</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
  • 配置文件
  • 因為實現分布式事務,所以一會再啟動一個9000端口的該項目
# 應用名稱
spring.application.name=arcdemo
# 應用服務 WEB 訪問端口
server.port=8000


# Redis數據庫索引(默認為0)
spring.redis.database=0
# Redis服務器地址
spring.redis.host=127.0.0.1
# Redis服務器連接端口
spring.redis.port=6379
# Redis服務器連接密碼(默認為空)
spring.redis.password=
# 連接池最大連接數(使用負值表示沒有限制)
spring.redis.jedis.pool.max-active=20
# 連接池最大阻塞等待時間(使用負值表示沒有限制)
spring.redis.jedis.pool.max-wait=-1
# 連接池中的最大空閑連接
spring.redis.jedis.pool.max-idle=10
# 連接池中的最小空閑連接
spring.redis.jedis.pool.min-idle=0
# 連接超時時間(毫秒)
spring.redis.timeout=1000
  • 在主啟動類注入Redisson
package 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
@EnableRedisHttpSession
public class ArcdemoApplication {
 

    public static void main(String[] args) {
 
        SpringApplication.run(ArcdemoApplication.class, args);
    }
    @Bean
    public Redisson redission() {
 
        Config config = new Config();
        config.useSingleServer().setAddress("redis://localhost:6379").setDatabase(0);
        return (Redisson) Redisson.create(config);
    }

}
  • 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
 */
@RestController
public 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 {
 
    //     //連接zk
    //     client = CuratorFrameworkFactory.newClient(ZK_ADDRESS,
    //             new RetryNTimes(10, 5000));
    //     client.start();
    // }

    // 分布式鎖
    @Autowired
    private Redisson redisson;

    @Resource
    private StringRedisTemplate StringRedisTemplate;


    @GetMapping("/login")
    public String login(String username, HttpSession session, HttpServletRequest request) {
 
        session.setAttribute("username", username);
        return username + ",端口" + request.getLocalPort();
    }

    @GetMapping("/getUser")
    public String getUser(HttpSession session, HttpServletRequest request) {
 
        String username = (String) session.getAttribute("username");
        return session.getId() + "," + username + ",端口" + request.getLocalPort();
    }

    @PostMapping("/checkTeacher")
    public String checkteacher(String teacherName) {
 
        // SpringBoot操作Redis
        String lockKey = "lockKey";
        RLock redissonLock = null;
        String num = "";
        try {
 
            redissonLock = redisson.getLock("lockKey");//加鎖
            redissonLock.tryLock(30, TimeUnit.SECONDS);//超時時間:每間隔10秒(1/3)
            num = stringRedisTemplate.opsForValue().get(teacherName);
            int n = Integer.parseInt(num);

            if (n > 0) {
 
                n = n - 1;
                stringRedisTemplate.opsForValue().set("lkz", n + "");
                //正常選擇老師
                System.out.println("當前名額:" + n);
            } else {
 
                return "名額已滿";
            }
        } catch (InterruptedException e) {
 
            e.printStackTrace();
        } finally {
 
            redissonLock.unlock();//釋放鎖
        }
        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("拿到了鎖");
    //             //業務邏輯
    //             num = stringRedisTemplate.opsForValue().get(teacherName);
    //             int n = Integer.parseInt(num);
    //             if (n > 0) {
 
    //                 n = n - 1;
    //                 stringRedisTemplate.opsForValue().set("lkz", n + "");
    //                 //正常選擇老師
    //                 System.out.println("當前名額:" + n);
    //             } else {
 
    //                 return "名額已滿";
    //             }
    //             // System.out.println("任務完畢,該釋放鎖了");
    //         }
    //     } catch (Exception e) {
 
    //         System.out.println("業務異常");
    //         e.printStackTrace();
    //     }finally {
 
    //         try {
 
    //             lock.release();
    //         } catch (Exception e) {
 
    //             System.out.println("釋放鎖異常");
    //             e.printStackTrace();
    //         }
    //     }
    //     return num;
    // }
}
  • redis需要有對應的key
set lkz 6

Redission和Zookeeper分別實現分布式鎖 - 天天要聞

1.3 啟動項目

  • 第一步:啟動redis,並且給lkz賦值
  • 第二步:啟動nginx,nginx需要做配置,指向本地的8000和9000端口
upstream testdev{
            server   127.0.0.1:8000 weight=1;
            server   127.0.0.1:9000 weight=1;
   }

    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            index  index.html index.htm;
            proxy_pass http://testdev;
            proxy_redirect default;
        }
  • 第三步:idea中啟動8000端口,並且再修改配置文件端口,再啟動9000端口

Redission和Zookeeper分別實現分布式鎖 - 天天要聞

點擊這個,然後修改9000即可同時啟動8000和9000端口

  • 第三步:啟動Jmeter,發請求

Redission和Zookeeper分別實現分布式鎖 - 天天要聞

Redission和Zookeeper分別實現分布式鎖 - 天天要聞

1.4 結果

Redission的結果自行查看,博主偷懶了在下面的zookeeper實現分布式鎖的結果才截圖了。

2、Zookeeper實現分布式鎖

2.1 前提準備

  • 下載好nginx(windows版本)
  • 下載好Jmeter(模仿高並發)
  • 下載好redis(windows版)
  • 下載好zookeeper(windows版本)和ZooInspector(可視化工具,也可以不下載)

2.2 代碼

  • pom文件
<?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">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <groupId>cn.lanqiao</groupId>
    <artifactId>arcdemo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>arcdemo</name>
    <description>arcdemo</description>


    <properties>
        <java.version>8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session-data-redis</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- redisson -->
        <dependency>
            <groupId>org.redisson</groupId>
            <artifactId>redisson-spring-boot-starter</artifactId>
            <version>3.17.5</version>
        </dependency>
    <!--    zookeeper和curator-->
        <dependency>
            <groupId>org.apache.zookeeper</groupId>
            <artifactId>zookeeper</artifactId>
            <version>3.5.7</version>
        </dependency>
        <dependency>
            <groupId>org.apache.curator</groupId>
            <artifactId>curator-framework</artifactId>
            <version>4.3.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.curator</groupId>
            <artifactId>curator-recipes</artifactId>
            <version>4.3.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.curator</groupId>
            <artifactId>curator-client</artifactId>
            <version>4.3.0</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-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
 */
@RestController
public 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 {
 
        //連接zk
        client = CuratorFrameworkFactory.newClient(ZK_ADDRESS,
                new RetryNTimes(10, 5000));
        client.start();
    }

    // 分布式鎖
    // @Autowired
    // private Redisson redisson;

    @Resource
    private StringRedisTemplate stringRedisTemplate;


    @GetMapping("/login")
    public String login(String username, HttpSession session, HttpServletRequest request) {
 
        session.setAttribute("username", username);
        return username + ",端口" + request.getLocalPort();
    }

    @GetMapping("/getUser")
    public String getUser(HttpSession session, HttpServletRequest request) {
 
        String username = (String) session.getAttribute("username");
        return session.getId() + "," + username + ",端口" + request.getLocalPort();
    }

    // @PostMapping("/checkTeacher")
    // public String checkteacher(String teacherName) {
 
    //     // SpringBoot操作Redis
    //     String lockKey = "lockKey";
    //     RLock redissonLock = null;
    //     String num = "";
    //     try {
 
    //         redissonLock = redisson.getLock("lockKey");//加鎖
    //         redissonLock.tryLock(30, TimeUnit.SECONDS);//超時時間:每間隔10秒(1/3)
    //         num = stringRedisTemplate.opsForValue().get(teacherName);
    //         int n = Integer.parseInt(num);
    //
    //         if (n > 0) {
 
    //             n = n - 1;
    //             stringRedisTemplate.opsForValue().set("lkz", n + "");
    //             //正常選擇老師
    //             System.out.println("當前名額:" + n);
    //         } else {
 
    //             return "名額已滿";
    //         }
    //     } catch (InterruptedException e) {
 
    //         e.printStackTrace();
    //     } finally {
 
    //         redissonLock.unlock();//釋放鎖
    //     }
    //     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("拿到了鎖");
                //業務邏輯
                num = stringRedisTemplate.opsForValue().get(teacherName);
                int n = Integer.parseInt(num);
                if (n > 0) {
 
                    n = n - 1;
                    stringRedisTemplate.opsForValue().set("lkz", n + "");
                    //正常選擇老師
                    System.out.println("當前名額:" + n);
                } else {
 
                    return "名額已滿";
                }
                // System.out.println("任務完畢,該釋放鎖了");
            }
        } catch (Exception e) {
 
            System.out.println("業務異常");
            e.printStackTrace();
        }finally {
 
            try {
 
                lock.release();
            } catch (Exception e) {
 
                System.out.println("釋放鎖異常");
                e.printStackTrace();
            }
        }
        return num;
    }
}

2.3 啟動項目

  • 第一步:啟動redis,並且給lkz賦值
  • 第二步:啟動nginx,nginx需要做配置,指向本地的8000和9000端口
upstream testdev{
            server   127.0.0.1:8000 weight=1;
            server   127.0.0.1:9000 weight=1;
   }

    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            index  index.html index.htm;
            proxy_pass http://testdev;
            proxy_redirect default;
        }
  • 第三步:idea中啟動8000端口,並且再修改配置文件端口,再啟動9000端口

Redission和Zookeeper分別實現分布式鎖 - 天天要聞

點擊這個,然後修改9000即可同時啟動8000和9000端口

  • 第三步:啟動zookeeper,並且啟動ZooInspector可視化工具
  • 第四步:啟動Jmeter,發請求

Redission和Zookeeper分別實現分布式鎖 - 天天要聞

Redission和Zookeeper分別實現分布式鎖 - 天天要聞

2.4 結果

Redission和Zookeeper分別實現分布式鎖 - 天天要聞

Redission和Zookeeper分別實現分布式鎖 - 天天要聞

看到控制台的輸出,可以看出來分布式鎖起作用了,並且可以觀看ZooInspector進行查看

Redission和Zookeeper分別實現分布式鎖 - 天天要聞

因為這裡採用的是有序臨時鎖,所以請求發完之後就刪除了鎖。必須在發起請求的一瞬間去刷新,才可能看到排好序的鎖。

3、 案例源碼地址

https://github.com/Guoleyuan/arcdemo

科技分類資訊推薦

長安與東風重組新進展:朱華榮稱不會改變長安既定戰略 - 天天要聞

長安與東風重組新進展:朱華榮稱不會改變長安既定戰略

2月9日,長安汽車和東風集團股份(00489.HK)同步發布了控股股東“正在與其他國資央企集團籌劃重組事項”的信息。長安汽車的控股股東是兵裝集團,而東風集團股份的控股股東是東風公司。隨即,長安汽車和東風集團這兩家汽車央企將合併重組,成為業內關注的焦點。
公安部出手了!年齡限制放寬10年、送考下鄉,2025年考駕照不難了 - 天天要聞

公安部出手了!年齡限制放寬10年、送考下鄉,2025年考駕照不難了

電動車加強管理以後,要求機動車類型的車輛需要持證上路,但是老年人考駕照卻受阻,一方面有年齡的限制,另一方面偏遠山區考駕照不方便,所以在2025年公安部出手了,年齡限制放寬10年,同時推出送考下鄉服務,還進一步的降低考駕照的費用,2025年起考摩托車駕照不難了。
從“星靈安全守護體系”到昊鉑HL,看懂廣汽科技日 - 天天要聞

從“星靈安全守護體系”到昊鉑HL,看懂廣汽科技日

發布會以技術切入,並全程圍繞安全展開。廣汽集團董事長、總經理馮興亞率先登場,宣布2025年四季度將正式上市支持L3級智能駕駛的車型,他同時強調面向自動駕駛時代對智能駕駛技術、整車安全架構以及突發風險處理能力的要求更高。如何才能滿足更高的要求?馮興亞提到了“廣汽
關稅大棒下,最受傷的車企出現了 - 天天要聞

關稅大棒下,最受傷的車企出現了

特朗普的關稅大棒剛揮出,尚未嚇退“外敵”,卻先刺痛了自己。近日,擁有瑪莎拉蒂、Jeep等14個品牌的全球第四大車企斯泰蘭蒂斯突然宣布裁撤900名美國工人,關閉加拿大和墨西哥兩家工廠,北美生產線陷入癱瘓。幾乎同一時間,捷豹路虎宣布暫停對美出口一個月,奧迪更是直接