分布式锁-简单入门

2023-05-16

状态不是很好,记一下以前学过的分布式锁吧。

样例简介

不谈大概念,就是简单入门以及使用。

为什么要用分布式锁呢?

假设我需要一个定时操作,每天在某个点,我要处理一批数据,要先从数据库中查询出来(IO操作),然后再逐步处理数据(CPU操作)。这些数据之间没有关联关系,不需要考虑数据执行的先后顺序。

单机思路

在单机情况下,做法是什么。开启一个定时任务,该任务中,查询数据库得到所有数据并加载到内存中。在内存中,我可以通过JUC的一些工具类,LinkedBlockingQueue保证线程安全的情况下移除元素,一个个的来处理。这是一种多线程的方案。

那么多进程呢,集群情况下,多台主机,该怎么处理。

多进程思路

分布式锁结合MQ实现解决方案。我说一下个人想法的一种解决方法,具体操作:

1.要定时处理数据,肯定是需要定时任务的。那么,三台主机都配置了定时任务。但是,从数据库中查询出数据的这一步我却只想执行一次,而不是三个主机各执行一次。在这里,就用到分布式锁了,我们可以使用tryLock方式,对其进行试图获取锁,同一个时刻,肯定只有一个任务获取到锁。剩下的两个获取失败就不执行了。我们就获取到这个数据。

2.在获取到这个数据后,可以选择将查询到数据推送至MQ,然后三台主机作为消费者,来有效提升系统的执行速率。

这是我内心中比较倾向的一种解决方式。性能相对高一点。

想想不高的,如同单机的这种方式,我们该怎么实现(不涉及中间件这种)。说一个相对耗性能的方案。也利用了分布式锁。

我要处理的数据,这个数据表中我加一个状态,0标识未处理,1标识处理。

1.加分布式锁。

2.查询出数据表中状态为0的单条数据。

3.做涉及到这条数据的一系列业务操作。

4.修改当前数据的状态为1。

5.解分布式锁。

有多少条数据就得加锁解锁多少次,以及查询多次数据库。性能的低下可想而之。

代码

例子说完了,用代码来体现一下。分布式锁我采用的是reddision的方式。这里就为了代码简单,模拟一个火车票数量减少的操作。(数据虽然放到redis了,而且redis执行是单线程的,但可以java代码将减少这个操作的过程设置为线程不安全的操作,这个样例中我是这么做的)。

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>
    <groupId>com.bo</groupId>
    <artifactId>distributed-lock-three</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>distributed-lock-three</name>
    <description>distributed-lock-three</description>

    <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <spring-boot.version>2.3.7.RELEASE</spring-boot.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>2.0.17</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <version>${spring-boot.version}</version>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.24</version>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <version>${spring-boot.version}</version>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
            <version>${spring-boot.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.12.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.redisson</groupId>
            <artifactId>redisson</artifactId>
            <version>3.17.7</version>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring-boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.3.7.RELEASE</version>
                <configuration>
                    <mainClass>com.bo.distributedlockthree.DistributedLockThreeApplication</mainClass>
                </configuration>
                <executions>
                    <execution>
                        <id>repackage</id>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

Redisson注册的代码

package com.bo.distributedlockthree.test.config;


import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

/**
 * @Auther: zeroB
 * @Date: 2022/11/14 09:53
 * @Description:
 */
@Component
public class TestDistributedLockConfig {
    @Bean
    public RedissonClient redissonClient(){
        Config config = new Config();
        config.useSingleServer().setAddress("redis://192.168.140.130:6379").setPassword("2wsx@WSX");
        RedissonClient redissonClient = Redisson.create(config);
        return redissonClient;
    }


}

返回结果类

package com.bo.distributedlockthree.test.pojo;

import java.io.Serializable;

/**
 * @Auther: zeroB
 * @Date: 2022/11/14 11:10
 * @Description:
 */
public class ResultVO<T> implements Serializable {
    private boolean isSuccess;

    private String errorMsg;

    private T data;

    public boolean isSuccess() {
        return isSuccess;
    }

    public void setSuccess(boolean success) {
        isSuccess = success;
    }

    public String getErrorMsg() {
        return errorMsg;
    }

    public void setErrorMsg(String errorMsg) {
        this.errorMsg = errorMsg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }
}

工具代码

package com.bo.distributedlockthree.test.action;

import com.bo.distributedlockthree.test.config.properties.ApplicationUtils;
import com.bo.distributedlockthree.test.pojo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RAtomicLong;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

/**
 * @Auther: zeroB
 * @Date: 2022/11/14 09:48
 * @Description:
 */
@Controller
@Slf4j
public class TestAction {
    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private ApplicationUtils applicationUtils;

    /**
     * 在redis中添加共享数据
     */
    @RequestMapping("testAddData")
    @ResponseBody
    public void testAddData(){
        RAtomicLong atomicLong = redissonClient.getAtomicLong("ticketCount");
        long l = atomicLong.addAndGet(1000L);
        log.info("存放至redis中的数据为{}",l);
    }


    /**
     * 测试下分布式锁,多进程共享数据存放至redis中
     */
    @RequestMapping("/testLock")
    @ResponseBody
    public String testLock(){

        RLock testLock = redissonClient.getLock("testLock");
        long l = 0L;
        try{
            testLock.lock();
            RAtomicLong ticketCount = redissonClient.getAtomicLong("ticketCount");
            long l1 = ticketCount.get();
            //如果这里不加判定,是不会存在异常的,但加上的话,就有可能出现减为0的情况了
            if(l1 <= 0){
                log.info("销售完成,销售数量为{}",l1);
                throw new UnsupportedOperationException("销售完成,已不支持");
            }
            //这里感觉用过CAS了,本质上已经同步处理过了
            Thread.sleep(500);
            l = ticketCount.decrementAndGet();
            log.info("减去后的值为"+l);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            testLock.unlock();
            return String.valueOf(l);
        }
    }

    /**
     * 得到容器内存放所有元素
     * @param name 容器内元素名称
     * @return
     * TODO 前端序列化传输展示存在问题,先不考虑这个问题
     */
    @RequestMapping("/listContainerData")
    @ResponseBody
    public ResultVO<List<Object>> listContainerData(String name){
        ResultVO<List<Object>> listResultVO = new ResultVO<>();
        if(StringUtils.isEmpty(name)){
            log.info("查询出全部的容器内容");
            listResultVO.setData(applicationUtils.listBean());
            return listResultVO;
        }
        List<Object> objects = new ArrayList<>();

        //需要序列化
        objects.add(applicationUtils.getBean(name));

        listResultVO.setData(objects);
        return listResultVO;
    }

    /**
     * 分布式锁测试tryLock方案的问题
     * @return
     */
    @RequestMapping("tryLockTest")
    @ResponseBody
    public ResultVO<String> tryLockTest(){
        RLock testLock = redissonClient.getLock("testLock");
        ResultVO<String> resultVO = new ResultVO<>();

        long l1 = 0L;
        //相当于结合CAS的dowhile循环,只有获取到锁的情况下,执行了我要执行的任务,结束了,所有的请求我都要得到并处理
        //但这样,一直获取不到锁,进程饥渴的情况下,会一直占用CPU,阻塞的,这个得想想方案
        while(true){
            //这块应该得加锁,因为这个值结果和判断条件是相关的,假如我不放到锁中的话
            /**
             * 1.我得到count是0了
             * 2.此时其它进程得到系统的值然后操作
             * 3.此时实际是小于0了,但依旧正常操作
             */
            if(!testLock.tryLock()){
                continue;
            }
            try{
                RAtomicLong ticketCount = redissonClient.getAtomicLong("ticketCount");
                long l = ticketCount.get();
                if(l <= 0){
                    log.info("售票已经执行完成了,售票结果为{}",l);
                    throw new UnsupportedOperationException("售票已经执行完成了,售票结果为"+l);
                }

                Thread.sleep(100);
                l1 = ticketCount.decrementAndGet();
                log.info("销售完成的结果为{}",l1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                testLock.unlock();
                resultVO.setData(String.valueOf(l1));
                return resultVO;
            }
        }

    }


}

总结

上述的测试可以通过,只是一个简单样例,来理解一下它的思想。其实真正使用的时候吧,配置之类的肯定是不简单的。我也没有实际生产用过,只是先提供给大家一个思路。

附上Redisson官方文档地址,有中文实在太贴心了:

目录 · redisson/redisson Wiki · GitHubicon-default.png?t=M85Bhttps://github.com/redisson/redisson/wiki/%E7%9B%AE%E5%BD%95

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

分布式锁-简单入门 的相关文章

随机推荐

  • k8s部署教程

    https mp weixin qq com s biz 61 MzI5MjA5Mjg5OA 61 61 amp mid 61 2247484395 amp idx 61 1 amp sn 61 0767cc24ec99ce818e41f7
  • Win10笔记本用雷电3接口外接显卡加速tensorflow深度学习步骤

    简介 xff1a 最近入手了一块rtx3060 xff0c 但自己的主力设备是笔记本 xff0c 于是萌生了通过外接显卡来加速深度学习的想法 xff0c 配置过程中遇到一些小问题 xff0c 经过调试最后解决了 xff0c 现在简单把整个过
  • 使用GitHub和DockerHub自动构建并发布镜像

    要使用自动构建 xff0c 必须在 Docker Hub 和GitHub上拥有一个帐户 首先登录您的Docker Hub账号 xff0c 创建一个Repository xff0c 创建类似如下页面 点击创建的Repository xff0c
  • 三 机器人仿真软件Gazebo介绍

    ROS教程 这是小弟的学习笔记 xff0c 有错求请拍 xff0c 多指教 xff0c 谢谢 三 机器人仿真软件Gazebo介绍 Gazebo功能 1 构建机器人运动仿真模型 在Gazebo里 xff0c 提供了最基础的三个物体 xff0c
  • Protobuf生成Go代码指南

    这个教程中将会描述protocol buffer编译器通过给定的 proto会编译生成什么Go代码 教程针对的是proto3版本的protobuf 在阅读之前确保你已经阅读过Protobuf语言指南 编译器调用 Protobuf核心的工具集
  • ROS sensor_msgs/LaserScan Message简单说明

    std msgs Header header float32 angle min 开始扫描角度 float32 angle max 结束扫描角度 float32 angle increment 每次扫描增加的角度 xff08 角度分辨率 x
  • 双系统Ubuntu分区

    假设整个空闲空间有200G xff0c 主要分4个区 xff1a 1 给系统分区EFI xff1a 在唯一的一个空闲分区上添加 xff0c 大小200M xff0c 逻辑分区 xff0c 空间起始位置 xff0c 用于efi xff1b 这
  • 2 用D435i运行VINS-fusion

    文章目录 1 VINS fusion的安装1 1 环境和依赖的安装1 2 编译VINS Fusion1 3 编译错误解决方法 2 VINS Fusion跑数据集3 用相机运行VINS Fusion 环境 xff1a Ubuntu20 04
  • Python每日一个小程序

    前几天上网 xff0c 收集了20多道Python练习题 这些练习题还是很有价值的 xff0c 正好最近忙着复习准备校招 xff0c 可以用来练手 我会把每道题都写一篇博客详细阐述解题思路和源代码 xff0c 在每道题目后面附上博客地址 希
  • 数分下(第1讲):一阶微分方程的三类模型求解

    第1 1讲 xff1a 一阶微分方程的解法 第一周第一讲将用3个小时时间 xff0c 完整讲解一阶微分方程y 61 f x y 的三种典型模型求解方法 掌握以下知识点 xff0c 并熟练做题训练 对应同济高数教材第七章1 4节 知识点脑图如
  • 非常详细的 Linux C/C++ 学习路线总结!助我拿下腾讯offer

    点击关注上方 五分钟学算法 xff0c 设为 置顶或星标 xff0c 第一时间送达干货 转自后端技术学堂 正文 我的另一篇文章 腾讯 C 43 43 后台开发面试笔试知识点参考笔记 整理了 C 43 43 后台开发知识点 xff0c 本文尝
  • 一线互联网公司程序员技术面试的流程以及注意事项

    先来了解面试的流程是什么 xff0c 然后再一一做准备 xff01 企业一般通过几轮技术面试来考察大家的各项能力 xff0c 一般流程如下 xff1a 一面机试 xff1a 一般会考选择题和编程题 二面基础算法面 xff1a 就是基础的算法
  • 为什么C++永不过时?

    Linus曾说过 xff1a C 43 43 是一门很恐怖的语言 xff0c 而比它更恐怖的是很多不合格的程序员在使用着它 xff01 这足以说明C 43 43 有多难 xff01 不过 xff0c 你也要明白 难度越高意味着含金量与竞争力
  • STM32 USB学习笔记6

    主机环境 xff1a Windows 7 SP1 开发环境 xff1a MDK5 14 目标板 xff1a STM32F103C8T6 开发库 xff1a STM32F1Cube库和STM32 USB Device Library 现在来分
  • Invalid bound statement (not found)

    目录 一 遇到的问题 二 分析思路 1 映射文件 2 测试类 三 解决方案 一 遇到的问题 前几日 xff0c 有个工作不久的同事找我帮他解决一个 Mybatis 的问题 他写了一个增删改查 xff0c 但是在启动程序的时候报错 xff1a
  • ThinkPHP6 解决小程序调用接口返回错误是网页的尴尬

    背景 早在开始了解ThinkPHP时就一直记得一段话 xff1a 在一开始无知的我以为出现错误后能在调试阶段优雅的了解错误信息 xff0c 但结果大家试一下便知道 xff0c 十分尴尬 尤其是当在小程序里请求api xff0c 在过程中发生
  • 大数据技术Canal总结和详细案例

    0 Canal介绍 Canal 是用 Java 开发的基于数据库增量日志解析 xff0c 提供增量数据订阅 amp 消费的中间件 目前Canal 主要支持了 MySQL 的 Binlog 解析 xff0c 解析完成后才利用 Canal Cl
  • T507 Ubuntu18.04 LXDE桌面汉化

    本文硬件平台采用飞凌T507开发板 xff0c 主要讲解Ubuntu图形桌面LXDE如何修改为中文界面 xff0c 本文使用的思路和方法仅供参考使用 xff0c 其它arm开发板虽然芯片不同 xff0c 但思路和方法有很多的共性 xff0c
  • 工作站和台式机的区别

    转自 xff1a 微点阅读 xff08 www weidianyuedu com xff09 微点阅读 范文大全 免费学习网站 工作站电脑非常高配 xff0c 那么它和台式机有什么区别呢 下面由小编给你做出详细的工作站和台式机区别介绍 希望
  • 分布式锁-简单入门

    状态不是很好 xff0c 记一下以前学过的分布式锁吧 样例简介 不谈大概念 xff0c 就是简单入门以及使用 为什么要用分布式锁呢 xff1f 假设我需要一个定时操作 xff0c 每天在某个点 xff0c 我要处理一批数据 xff0c 要先