当前位置: 移动技术网 > IT编程>开发语言>Java > SpringBoot中使用redis做分布式锁的方法

SpringBoot中使用redis做分布式锁的方法

2020年09月11日  | 移动技术网IT编程  | 我要评论
一.模拟问题最近在公司遇到一个问题,挂号系统是做的集群,比如启动了两个相同的服务,病人挂号的时候可能会出现同号的情况,比如两个病人挂出来的号都是上午2号.这就出现了问题,由于是集群部署的,所以单纯在代

一.模拟问题

最近在公司遇到一个问题,挂号系统是做的集群,比如启动了两个相同的服务,病人挂号的时候可能会出现同号的情况,比如两个病人挂出来的号都是上午2号.这就出现了问题,由于是集群部署的,所以单纯在代码中的方法中加锁是不能解决这种情况的.下面我将模拟这种情况,用redis做分布式锁来解决这个问题.

1.新建挂号明细表

2.在idea上新建项目

下图是创建好的项目结构,上面那个parent项目是其他项目不用管它,和新建的没有关系

3.开始创建controller,service,dao(mapper),写好后整体结构如下

这里贴上service实现类的代码,主要代码就是这一块:

package com.zk.service.impl;
 
import com.zk.mapper.mzmapper;
import com.zk.service.mzservice;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.stereotype.service;
import java.util.hashmap;
import java.util.map;
 
/**
 * 门诊操作service实现类
 *
 * @author zk
 * @date 2020-9-9
 */
@service
public class mzserviceimpl implements mzservice {
 @autowired
 private mzmapper mzmapper;
 
 @override
 public map<string, object> gh(string ksdm, string ysdm,string brid) {
  map<string,object> resultmap = new hashmap<>();
  int ghxh = 0;
  //获取当前的挂号序号
  map<string, object> ghxhmap = mzmapper.getghxh(ksdm,ysdm);
  //如果为空,说明还没有人挂这个医生的号,当前是一号
  if(ghxhmap == null){
   ghxh = 1;
  }else{
   ghxh = (int)ghxhmap.get("ghxh");
   ghxh++;
  }
  //实际场景中,先获取到ghxh后,还会进行收费等其他操作,这里模拟一下需要耗费时间,为了方便测试出现问题,这里时间设置稍微长一点
  try {
   thread.sleep(2000);
  } catch (interruptedexception e) {
   e.printstacktrace();
  }
  //新增挂号明细记录
  mzmapper.addghmx(ksdm,ysdm,ghxh,brid);
  resultmap.put("code","200");
  resultmap.put("msg","success");
  return resultmap;
 }
}

4.进行测试

1)清空数据库表

2)使用postman发送post请求,假设ksdm=1表示皮肤科,ysdm=1表示医生华佗,brbh=1表示张三,现在张三去医院挂皮肤科华佗医生的号,收费员就会操作系统调用上面写的挂号接口.

调用成功后,看看数据库里的数据

可以看到张三挂到了华佗医生的第一个号,接着把请求参数的brbh改成2表示李四,李四也去挂华佗医生的号

请求成功后查看数据库

可以看到李四挂了华佗医生的第二个号.现在就是正常的挂号,没有出现问题.

3)postman开第二个请求窗口,两个窗口同时去掉接口进行挂号

窗口一模拟张三挂号

窗口二模拟李四挂号

操作成功后看看数据库

结果是张三和李四都挂到了三号,这就出现了线程安全问题.

3)使用加锁的方式解决问题

方法加上锁之后,测试确实没有问题了,但是实际情况是集群部署的,并不是只有一个服务

4)启动两个服务

idea中设置允许启动多个实例

修改端口号,第一个启动的端口号是8080,这里改成8081

5)启动两个服务后再用postman去请求,张三请求8080服务接口

李四请求8081接口

两个窗口同时请求的时候,再次出现了ghxh相同的情况,在方法上加同步锁不能解决这个问题.

二.使用redis做分布式锁解决问题

1.首先需要启动一个redis,如果不知道redis怎么安装使用的,可以看我之前写的"redis的安装和使用".因为之前我在虚拟机上安装过了redis,这里直接启动一个单节点redis

2.项目的pom.xml文件引入redis依赖

<dependency>
 <groupid>org.springframework.boot</groupid>
 <artifactid>spring-boot-starter-data-redis</artifactid>
</dependency>

3.在application.yml中配置redis

spring:
 redis:
 host: 192.168.1.6
 port: 6379

4.新建redis锁操作类

package com.zk.util;
 
import org.apache.commons.lang3.stringutils;
import org.springframework.data.redis.core.stringredistemplate;
import org.springframework.stereotype.repository;
 
import java.util.uuid;
import java.util.concurrent.timeunit;
 
/**
 * redis锁操作类
 *
 * @author zk
 * @date 2020-9-10
 */
@repository
public class redislock {
 
 private stringredistemplate stringredistemplate;
 
 public redislock(stringredistemplate stringredistemplate) {
  this.stringredistemplate = stringredistemplate;
 }
 
 /**
  * 加锁,无阻塞
  * 加锁过程必须设置过期时间
  * 如果没有设置过期时间,手动释放锁的操作出现问题,那么就发生死锁,锁永远不能被释放.
  * 加锁和设置过期时间过程必须是原子操作
  * 如果加锁后服务宕机或程序崩溃,来不及设置过期时间,同样会发生死锁.
  *
  * @param key 锁id
  * @param expire 过期时间
  * @return
  */
 public string trylock(string key, long expire) {
  string token = uuid.randomuuid().tostring();
  //setifabsent方法:当key不存在的时候,设置成功并返回true,当key存在的时候,设置失败并返回false
  //token是对应的value,expire是缓存过期时间
  boolean issuccess = stringredistemplate.opsforvalue().setifabsent(key, token, expire, timeunit.milliseconds);
  if (issuccess) {
   return token;
  }
  return null;
 }
 
 /**
  * 加锁,有阻塞
  *
  * @param name 锁名称
  * @param expire 锁过期时间
  * @param timeout 请求超时时间
  * @return
  */
 public string lock(string name, long expire, long timeout) {
  long starttime = system.currenttimemillis();
  string token;
  do {
   token = trylock(name, expire);
   if (token == null) {
    if ((system.currenttimemillis() - starttime) > (timeout - 50)) {
     break;
    }
    try {
     //try 50 per sec
     thread.sleep(50);
    } catch (interruptedexception e) {
     e.printstacktrace();
     return null;
    }
   }
  } while (token == null);
 
  return token;
 }
 
 /**
  * 解锁操作
  * 解锁必须是解除自己加上的锁
  * 试想一个这样的场景,服务a加锁,但执行效率非常慢,导致锁失效后还未执行完,但这时候服务b已经拿到锁了,这时候服务a执行完毕了去解锁,
  * 把服务b的锁给解掉了,其他服务c、d、e...都可以拿到锁了,这就有问题了.
  * 加锁的时候我们可以设置唯一value,解锁时判断是不是自己先前的value就行了.
  *
  * @param key
  * @param token
  * @return
  */
 public boolean unlock(string key, string token) {
  //解锁时需要先取出key对应的value进行判断是否相等,这也是为什么加锁的时候需要放不重复的值作为value
  string value = stringredistemplate.opsforvalue().get("name");
  if (stringutils.equals(value, token)) {
   stringredistemplate.delete(key);
   return true;
  }
  return false;
 }
}

5.修改业务操作类,用上redislock

package com.zk.service.impl;
 
import com.zk.mapper.mzmapper;
import com.zk.service.mzservice;
import com.zk.util.redislock;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.stereotype.service;
 
import java.util.hashmap;
import java.util.map;
 
/**
 * 门诊操作service实现类
 *
 * @author zk
 * @date 2020-9-9
 */
@service
public class mzserviceimpl implements mzservice {
 @autowired
 private mzmapper mzmapper;
 @autowired
 private redislock redislock;
 
 @override
 public map<string, object> gh(string ksdm, string ysdm, string brid) {
  map<string, object> resultmap = new hashmap<>();
  int ghxh = 0;
  //加锁操作
  string token = null;
  token = redislock.lock("gh", 3000,3500);
  try {
   //获取到了锁,执行正常业务
   if (token != null) {
    //获取当前的挂号序号
    map<string, object> ghxhmap = mzmapper.getghxh(ksdm, ysdm);
    //如果为空,说明还没有人挂这个医生的号,当前是一号
    if (ghxhmap == null) {
     ghxh = 1;
    } else {
     ghxh = (int) ghxhmap.get("ghxh");
     ghxh++;
    }
    //实际场景中,先获取到ghxh后,还会进行收费等其他操作,这里模拟一下需要耗费时间,为了方便测试出现问题,这里时间设置稍微长一点
    try {
     thread.sleep(2000);
    } catch (interruptedexception e) {
     e.printstacktrace();
    }
    //新增挂号明细记录
    mzmapper.addghmx(ksdm, ysdm, ghxh, brid);
   } else {
    resultmap.put("code", "401");
    resultmap.put("msg", "其他窗口正在操作,请稍后再试");
    return resultmap;
   }
  } finally {
   //解锁
   if (token != null) {
    boolean gh = redislock.unlock("gh", token);
   }
  }
  resultmap.put("code", "200");
  resultmap.put("msg", "success");
  return resultmap;
 }
}

6.再用postman开两个窗口去请求,和上面的操作一样,然后再看数据库的数据

问题解决,不会再出现重复的ghxh.

总结

到此这篇关于springboot中使用redis做分布式锁的方法的文章就介绍到这了,更多相关springboot redis分布式锁内容请搜索移动技术网以前的文章或继续浏览下面的相关文章希望大家以后多多支持移动技术网!

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网