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

科技分類資訊推薦

所謂「大而美」法案或將繼續擴大美債規模 - 天天要聞

所謂「大而美」法案或將繼續擴大美債規模

美國所謂「大而美」法案7月1日在國會參議院得到通過,當前還需要得到眾議院的通過才能提交給美國總統簽字。如果該法案最終通過並成為法律,預計將對已創下紀錄的美國聯邦政府債務增加壓力。美國國會預算辦公室估....
解碼哈葯618 突圍路徑:從產品矩陣到生態構建的行業示範 - 天天要聞

解碼哈葯618 突圍路徑:從產品矩陣到生態構建的行業示範

當 2025 年 "618" 電商大促成為檢驗消費市場韌性的試金石,哈葯以國民葯企的戰略定力與創新突破,構建起一套 "傳統賽道築基 + 新興領域破局" 的增長模型。在保健品行業競爭白熱化的背景下,這家企業通過多品牌協同、產品創新迭代與數字化營銷破圈,不僅鞏固了細分市場領導地位,更以全鏈路生態布局為大健康產業提供了可複製...
更快,更強,更純粹!超薄極致電競利器ROG絕神OLED顯示器 - 天天要聞

更快,更強,更純粹!超薄極致電競利器ROG絕神OLED顯示器

熟悉鼠鼠我的朋友都知道我是一個遊戲愛好者,無論是喊上朋友們一起開黑還是自己沉浸式體驗製作精良的3A大作,都能在平時繁重的牛馬生活之餘帶給我放鬆和快樂。作為重度遊戲愛好者,外設的選擇自然是馬虎不得,這其中我最為看重的就是能夠直接影響平時遊戲體
坐飛機和高鐵分別可以攜帶什麼樣的充電寶? - 天天要聞

坐飛機和高鐵分別可以攜帶什麼樣的充電寶?

來源:【江西發佈】近日民航局禁止攜帶沒有3C標識、被召回範圍的充電寶上機規定引發關注坐飛機和高鐵分別可以攜帶什麼樣的充電寶?充電寶上飛機乘坐飛機時,充電寶只能在手提行李中攜帶或隨身攜帶,嚴禁在託運行李中攜帶。
小米YU7「封神」 國產新能源汽車「新王換舊王」 - 天天要聞

小米YU7「封神」 國產新能源汽車「新王換舊王」

摘要:新能源的新格局,雛形已現。鳳凰網科技 出品2025年6月26日夜晚,小米旗下首款SUV車型小米YU 7正式發佈。這款以豪華、高性能、極致體驗、先進安全性為特徵的SUV車型,猶如一顆重磅核彈投入本就不平靜的新能源車市,激起千層浪。
百度前副總裁璩靜開醫美診所,人均消費2218元 - 天天要聞

百度前副總裁璩靜開醫美診所,人均消費2218元

紅星資本局7月2日消息,百度前副總裁璩靜在華為總部坂田基地附近開了一家醫美診所。據公開資料,璩靜名下新增一家存續企業——深圳大為診所。該診所成立於2024年12月23日,璩靜持股比例為100%,認繳出資額為100萬元,經營範圍為診所服務等。
千里智行,常用常新,傳祺嚮往S7 開啟重磅OTA升級 - 天天要聞

千里智行,常用常新,傳祺嚮往S7 開啟重磅OTA升級

7月2日,傳祺嚮往S7 OTA如期而至,OTA 2.0版本正式全量推送。本次升級新增16項功能,31項 功能升級和57項體驗優化,主要涉及智能座艙、智能輔助駕駛、娛樂系統、車機交互等多個維度,旨在為用戶提供常用常新的出行體驗,功能強大又好用。
九州風神推出大霜塔稜鏡風冷散熱器:雙塔稜鏡頂蓋,209 元 - 天天要聞

九州風神推出大霜塔稜鏡風冷散熱器:雙塔稜鏡頂蓋,209 元

IT之家 7 月 3 日消息,九州風神 DeepCool 現已推出大霜塔稜鏡 (AG620 ARGB V2) 風冷散熱器。其採用雙塔雙風扇六熱管直觸設計,雙塔頂部均配有 ARGB 燈效「稜鏡頂蓋」。大霜塔稜鏡長寬高 129×136×162 (mm),支持 45mm 高內存條。其六根 6mm 雙向恆定熱平衡熱管採用 CTT 2.0 核心觸控技術在塔體底部並管排