一、概述分布式锁的重要性不言而喻,原因不在赘述,每一位菜鸟都有理由掌握它。提到分布式锁,解决方案更是乌泱乌泱的,如:
直接通过关系型数据库实现基于Redission实现基于Apache Curator实现…本文暂时先介绍一种,基于Redission实现的方式
二、环境搭建有一个简单的SpringBoot环境即可,便于测试:
依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson</artifactId>
<version>3.6.5</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>配置server: port: 7077
spring: redis: host: 192.144.228.170 database: 01234567启动及配置类package com.ideax.distributed;
import org.redisson.Redisson;import org.redisson.api.RedissonClient;import org.redisson.config.Config;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.context.annotation.Bean;
Java技术迷
@SpringBootApplicationpublic class DistributedApplication { public static void main(String[] args) { SpringApplication.run(DistributedApplication.class,args); }
/*** 配置redisson客户端* @return org.redisson.Redisson* @author zhangxs* @date 2022-01-06 10:01*/@Beanpublic Redisson redisson(){// 单机模式Config config = new Config();config.useSingleServer().setAddress("redis://192.144.228.170:6379").setDatabase(0);return (Redisson) Redisson.create(config);}
}1234567891011121314151617181920212223242526272829三、模拟一个库存扣减的场景package com.ideax.distributed.controller;
import org.redisson.Redisson;import org.redisson.api.RLock;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.redis.core.StringRedisTemplate;import org.springframework.http.ResponseEntity;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;
import java.util.Objects;import java.util.UUID;import java.util.concurrent.TimeUnit;
/**
@date 2022-01-06 09:46*/@RequestMapping(“/inventory”)@RestControllerpublic class InventoryController { @Autowired private StringRedisTemplate redisTemplate;
@Autowired private Redisson redisson;
@GetMapping(“/minus”) public ResponseEntity<String> minusInventory(){
// 分布式高并发场景下,这样肯定不行synchronized (this) {int stock = Integer.parseInt(Objects.requireNonNull(redisTemplate.opsForValue().get("stock")));if (stock > 0) {int currentStock = stock - 1;redisTemplate.opsForValue().set("stock", currentStock + "");System.out.println("扣减成功,当前库存为" + currentStock);} else {System.out.println("库存不足,扣减失败!");}}return ResponseEntity.ok("success");
}
@GetMapping(“/minus1”) public ResponseEntity<String> minusInventory1(){
// 相当于setnx命令String lockKey = "lockKey";// 务必加try-finally,因为如果服务挂了,锁还得释放String clientId = UUID.randomUUID().toString();try {// 相当于加锁// Boolean absent = redisTemplate.opsForValue().setIfAbsent(lockKey, "zxs");// 上下两行不能分开写,如果这中间报异常了,依然出现死锁// redisTemplate.expire(lockKey,10, TimeUnit.SECONDS);Boolean absent = redisTemplate.opsForValue().setIfAbsent(lockKey, clientId,30,TimeUnit.SECONDS);if (!absent) {return ResponseEntity.notFound().build();}
int stock = Integer.parseInt(Objects.requireNonNull(redisTemplate.opsForValue().get("stock")));if (stock > 0) {int currentStock = stock - 1;redisTemplate.opsForValue().set("stock", currentStock + "");System.out.println("扣减成功,当前库存为" + currentStock);} else {System.out.println("库存不足,扣减失败!");}} finally {// 如果系统挂了呢,finally也不起作用了,因此还需要设置超时时间// 释放锁之前,判断一下,务必释放的锁是自己持有的锁if (clientId.equals(redisTemplate.opsForValue().get(lockKey))) {redisTemplate.delete(lockKey);}}return ResponseEntity.ok("success");}/*** 终极方案*/@GetMapping("/minus2")public ResponseEntity<String> minusInventory2(){// redisson解决方案String lockKey = "lockKey";RLock lock = redisson.getLock(lockKey);try {// 加锁lock.lock();int stock = Integer.parseInt(Objects.requireNonNull(redisTemplate.opsForValue().get("stock")));if (stock > 0) {int currentStock = stock - 1;redisTemplate.opsForValue().set("stock", currentStock + "");System.out.println("扣减成功,当前库存为" + currentStock);} else {System.out.println("库存不足,扣减失败!");}} finally {// 释放锁lock.unlock();}return ResponseEntity.ok("success");}
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105四、总结@GetMapping(“/minus”) public ResponseEntity<String> minusInventory():初步实现方式,在单线程环境下可以使用,但是在分布式高并发场景下,毫无疑问是肯定不行的@GetMapping(“/minus1”) public ResponseEntity<String> minusInventory1():进阶实现方式,在一般的不拘小节的公司,勉强够用,但是你需要考虑一下,锁过期时间,到底设置多少才能完美呢?@GetMapping(“/minus2”) public ResponseEntity<String> minusInventory2():终极实现方式,redisson帮我们解决了上面的实现方式出现的尴尬情况
相关推荐
© 2020 asciim码
人生就是一场修行