SpringBoot基于Redis的分布式锁实现

一、概述

分布式锁的重要性不言而喻,原因不在赘述,每一位菜鸟都有理由掌握它。提到分布式锁,解决方案更是乌泱乌泱的,如:

  • 直接通过关系型数据库实现
  • 基于Redission实现
  • 基于Apache Curator实现

  • 本文暂时先介绍一种,基于Redission实现的方式

二、环境搭建

有一个简单的SpringBoot环境即可,便于测试:

  • 依赖
<dependencies>
    <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-data-redisartifactId>
    dependency>
    <dependency>
        <groupId>org.redissongroupId>
        <artifactId>redissonartifactId>
        <version>3.6.5version>
    dependency>
    <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-webartifactId>
    dependency>
    <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-testartifactId>
        <scope>testscope>
    dependency>
dependencies>
  • 配置
server:
  port: 7077

spring:
  redis:
    host: 192.144.228.170
    database: 0
  • 启动及配置类
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;

@SpringBootApplication
public 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
     */
    @Bean
    public Redisson redisson(){
        // 单机模式
        Config config = new Config();
        config.useSingleServer().setAddress("redis://192.144.228.170:6379").setDatabase(0);
        return (Redisson) Redisson.create(config);
    }
}

三、模拟一个库存扣减的场景

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;

/**
 * 库存 前端控制器
 * @author zhangxs
 * @date 2022-01-06 09:46
 */
@RequestMapping("/inventory")
@RestController
public 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");
    }
}

四、总结

  • @GetMapping("/minus") public ResponseEntity minusInventory():初步实现方式,在单线程环境下可以使用,但是在分布式高并发场景下,毫无疑问是肯定不行的
  • @GetMapping("/minus1") public ResponseEntity minusInventory1():进阶实现方式,在一般的不拘小节的公司,勉强够用,但是你需要考虑一下,锁过期时间,到底设置多少才能完美呢?
  • @GetMapping("/minus2") public ResponseEntity minusInventory2():终极实现方式,redisson帮我们解决了上面的实现方式出现的尴尬情况

你可能感兴趣的:(微服务及架构,SpringBoot,redis,分布式,数据库)