溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

怎么在SpringBoot中使用Redisson實(shí)現(xiàn)一個分布式鎖

發(fā)布時間:2021-03-22 17:09:48 來源:億速云 閱讀:740 作者:Leah 欄目:編程語言

怎么在SpringBoot中使用Redisson實(shí)現(xiàn)一個分布式鎖?針對這個問題,這篇文章詳細(xì)介紹了相對應(yīng)的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。

1.1、引入Maven依賴

<dependency>
 <groupId>org.redisson</groupId>
 <artifactId>redisson-spring-boot-starter</artifactId>
 <version>3.10.6</version>
</dependency>

注意:我這里引入的是redisson和springboot的集成包,網(wǎng)上一些教程可能是引入如下配置

<dependency>
 <groupId>org.redisson</groupId>
 <artifactId>redisson</artifactId>
 <version>3.6.1</version>
</dependency>

如果你引入的就是redisson的依賴包,如果該依賴包的版本低于3.5會需要你再引入

<dependency>
 <groupId>io.netty</groupId>
 <artifactId>netty-all</artifactId>
 <version>4.1.25.Final</version>
</dependency>
 
<dependency>
 <groupId>com.fasterxml.jackson.core</groupId>
 <artifactId>jackson-core</artifactId>
 <version>2.9.0</version>
</dependency>
 
<dependency>
 <groupId>com.fasterxml.jackson.core</groupId>
 <artifactId>jackson-databind</artifactId>
 <version>2.9.0</version>
</dependency>

這樣的一些依賴。

1.2、配置redis信息

spring:
  application:
    name: spring-cloud-product
  redis:
    port: 6379
    host: 127.0.0.1
    password:
    database: 0
    timeout: 2000

1.3、配置redisson

怎么在SpringBoot中使用Redisson實(shí)現(xiàn)一個分布式鎖

新建一個redisson-single.yml的配置文件 下面是單機(jī)配置 

singleServerConfig:
 idleConnectionTimeout: 10000
 pingTimeout: 1000
 connectTimeout: 10000
 timeout: 3000
 retryAttempts: 3
 retryInterval: 1500
 reconnectionTimeout: 3000
 failedAttempts: 3
 password: null
 subscriptionsPerConnection: 5
 clientName: null
 address: "redis://127.0.0.1:6379"
 subscriptionConnectionMinimumIdleSize: 1
 subscriptionConnectionPoolSize: 50
 connectionMinimumIdleSize: 32
 connectionPoolSize: 64
 database: 0
 #在最新版本中dns的檢查操作會直接報(bào)錯 所以我直接注釋掉了
 #dnsMonitoring: false
 dnsMonitoringInterval: 5000
threads: 0
nettyThreads: 0
codec: !<org.redisson.codec.JsonJacksonCodec> {}
transportMode : "NIO"

1.4、寫一個RedissonConfig配置類 來配置你的redisson

/**
* @Description //TODO
* @Date $ $
* @Author huangwb
**/
@Configuration
public class RedssonConfig {
 @Bean(destroyMethod="shutdown")
 public RedissonClient redisson() throws IOException {
  RedissonClient redisson = Redisson.create(
    Config.fromYAML(new ClassPathResource("redisson-single.yml").getInputStream()));
  return redisson;
 }
}

1.5、編寫一個秒殺接口

@Autowired
private RedissonClient redissonClient;
 
@Override
public boolean decrementProductStore(Long productId, Integer productQuantity) {
 String key = "dec_store_lock_" + productId;
 RLock lock = redissonClient.getLock(key);
 try {
  //加鎖 操作很類似Java的ReentrantLock機(jī)制
  lock.lock();
  ProductInfo productInfo = productInfoMapper.selectByPrimaryKey(productId);
  //如果庫存為空
  if (productInfo.getProductStock() == 0) {
   return false;
  }
  //簡單減庫存操作 沒有重新寫其他接口了
  productInfo.setProductStock(productInfo.getProductStock() - 1);
  productInfoMapper.updateByPrimaryKey(productInfo);
 } catch (Exception e) {
  System.out.println(e.getMessage());
 } finally {
  //解鎖
  lock.unlock();
 }
 return true;
}

1.6、寫一個簡單的測試請求 

@GetMapping("test")
public String createOrderTest() {
 if (!productInfoService.decrementProductStore(1L, 1)) {
  return "庫存不足";
 }
 OrderMaster orderMaster = new OrderMaster();
 //未支付
 orderMaster.setOrderStatus(0);
 //未支付
 orderMaster.setPayStatus(0);
 orderMaster.setBuyerName(name);
 orderMaster.setBuyerAddress("湖南長沙");
 orderMaster.setBuyerPhone("18692794847");
 orderMaster.setOrderAmount(BigDecimal.ZERO);
 orderMaster.setCreateTime(DateUtils.getCurrentDate());
 orderMaster.setOrderId(UUID.randomUUID().toString().replaceAll("-", ""));
 orderMasterService.insert(orderMaster);
 return "創(chuàng)建訂單成功";
}

1.7、使用ab做接口測試

怎么在SpringBoot中使用Redisson實(shí)現(xiàn)一個分布式鎖

怎么在SpringBoot中使用Redisson實(shí)現(xiàn)一個分布式鎖

怎么在SpringBoot中使用Redisson實(shí)現(xiàn)一個分布式鎖

ab -n 300 -c 300 請求地址

-n 的含義就是你做多少個請求

-c 的含義就是多少個用戶并發(fā)請求

數(shù)據(jù)庫中的商品已經(jīng)全部被秒殺完 并未出現(xiàn)超庫存的情況。

關(guān)于怎么在SpringBoot中使用Redisson實(shí)現(xiàn)一個分布式鎖問題的解答就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注億速云行業(yè)資訊頻道了解更多相關(guān)知識。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI