SpringBoot使用Redisson实现分布式锁秒杀

本篇文章采用的是单机模式,具体可以参考官网redisson介绍。
 

Redisson源码分析

Redisson实现了Lock接口,对比Lock而言,是可重入锁,功能强大,源码复杂。

加锁

用代码举例子

public static void main(String[] args) {
    Config config = new Config();
    config.useSingleServer().setAddress("redis://127.0.0.1:6379");
    RedissonClient client = Redisson.create(config);
    RLock lock = client.getLock("lock1");
    try {
        // 加锁
        lock.lock();
    } finally {
        // 解锁
       lock.unlock();
    }
}

RLock lock = client.getLock("lock1");这句代码就是为了获取锁的实例。

查看 lock.lock(); 的源码

@Override
public void lock() {
    try {
        lockInterruptibly();
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }
}

查看 lockInterruptibly 方法

@Override
public void lockInterruptibly(long leaseTime, TimeUnit unit) throws InterruptedException {
    // 获取当前线程的id
    long threadId = Thread.currentThread().getId();
    // 尝试获取锁
    Long ttl = tryAcquire(leaseTime, unit, threadId);
    // lock acquired ,ttl为空,说明成功获取锁,返回
    if (ttl == null) {
        return;
    }

    // 如果获取锁失败,则订阅到对应这个锁的channel
    RFuture<RedissonLockEntry> future = subscribe(threadId);
    commandExecutor.syncSubscription(future);

    try {
        // 
        while (true) {
        	// 再次尝试获取锁
            ttl = tryAcquire(leaseTime, unit, threadId);
            // lock acquired , ttl为空,说明成功获取锁,返回
            if (ttl == null) {
                break;
            }

            // waiting for message , ttl大于0 则等待ttl时间后继续尝试获取
            if (ttl >= 0) {
                getEntry(threadId).getLatch().tryAcquire(ttl, TimeUnit.MILLISECONDS);
            } else {
                getEntry(threadId).getLatch().acquire();
            }
        }
    } finally {
        // 取消对channel的订阅
        unsubscribe(future, threadId);
    }
	// get(lockAsync(leaseTime, unit));
}

流程图:

查看 tryAcquireAsync 方法

private <T> RFuture<Long> tryAcquireAsync(long leaseTime, TimeUnit unit, final long threadId) {
    // 如果存在过期时间,按照正常费那事获取锁
    if (leaseTime != -1) {
        return tryLockInnerAsync(leaseTime, unit, threadId, RedisCommands.EVAL_LONG);
    }
    // 读取配置的默认加锁时间30秒执行获取锁的  private long lockWatchdogTimeout = 30 * 1000; 
    RFuture<Long> ttlRemainingFuture = tryLockInnerAsync(commandExecutor.getConnectionManager().getCfg().getLockWatchdogTimeout(), TimeUnit.MILLISECONDS, threadId, RedisCommands.EVAL_LONG);
    // 如果一直持有这个锁,开启监听通过定时任务不断刷新锁的过期时间
    ttlRemainingFuture.addListener(new FutureListener<Long>() {
        @Override
        public void operationComplete(Future<Long> future) throws Exception {
            if (!future.isSuccess()) {
                return;
            }

            Long ttlRemaining = future.getNow();
            // lock acquired
            if (ttlRemaining == null) {
                scheduleExpirationRenewal(threadId);
            }
        }
    });
    return ttlRemainingFuture;
}

继续看 tryLockInnerAsync 方法,采用LUA脚本代码加锁。

<T> RFuture<T> tryLockInnerAsync(long leaseTime, TimeUnit unit, long threadId, RedisStrictCommand<T> command) {
	// 设置过期时间
    internalLockLeaseTime = unit.toMillis(leaseTime);

    return commandExecutor.evalWriteAsync(getName(), LongCodec.INSTANCE, command,
    		  // 如果锁不存在,则通过hset设置它的值,并设置过期时间
              "if (redis.call('exists', KEYS[1]) == 0) then " +
                  "redis.call('hset', KEYS[1], ARGV[2], 1); " +
                  "redis.call('pexpire', KEYS[1], ARGV[1]); " +
                  "return nil; " +
              "end; " +
              // 如果锁已存在,并且锁的是当前线程,则通过hincrby给数值递增1
              "if (redis.call('hexists', KEYS[1], ARGV[2]) == 1) then " +
                  "redis.call('hincrby', KEYS[1], ARGV[2], 1); " +
                  "redis.call('pexpire', KEYS[1], ARGV[1]); " +
                  "return nil; " +
              "end; " +
              // //如果锁已存在,但并非本线程,则返回过期时间ttl
              "return redis.call('pttl', KEYS[1]);",
                Collections.<Object>singletonList(getName()), internalLockLeaseTime, getLockName(threadId));
}

加锁成功后,redis会存在加锁的hash结构数据,key为随机字符串+线程ID;value值为1。如果同一线程多次调用lock方法,值递增1。

解锁

@Override
public RFuture<Void> unlockAsync(final long threadId) {
    final RPromise<Void> result = new RedissonPromise<Void>();

    // 解锁方法
    RFuture<Boolean> future = unlockInnerAsync(threadId);

    future.addListener(new FutureListener<Boolean>() {
        @Override
        public void operationComplete(Future<Boolean> future) throws Exception {
            if (!future.isSuccess()) {
                cancelExpirationRenewal(threadId);
                result.tryFailure(future.cause());
                return;
            }

            Boolean opStatus = future.getNow();
            // 如果返回值为空,说明解锁个当前加锁不是一个线程,抛出异常
            if (opStatus == null) {
                IllegalMonitorStateException cause = new IllegalMonitorStateException("attempt to unlock lock, not locked by current thread by node id: "
                        + id + " thread-id: " + threadId);
                result.tryFailure(cause);
                return;
            }
            // 解说成功,取消刷新过期时间的定时任务
            if (opStatus) {
                cancelExpirationRenewal(null);
            }
            result.trySuccess(null);
        }
    });

    return result;
}

核心解锁代码

protected RFuture<Boolean> unlockInnerAsync(long threadId) {
    return commandExecutor.evalWriteAsync(getName(), LongCodec.INSTANCE, RedisCommands.EVAL_BOOLEAN,
    		// 如果锁已经不存在, 发布锁释放的消息
            "if (redis.call('exists', KEYS[1]) == 0) then " +
                "redis.call('publish', KEYS[2], ARGV[1]); " +
                "return 1; " +
            "end;" +
            // 如果释放锁的线程和已存在锁的线程不是同一个线程,返回null
            "if (redis.call('hexists', KEYS[1], ARGV[3]) == 0) then " +
                "return nil;" +
            "end; " +
            // 通过hincrby递减1的方式,释放一次锁
            // 若剩余次数大于0 ,则刷新过期时间
            "local counter = redis.call('hincrby', KEYS[1], ARGV[3], -1); " +
            "if (counter > 0) then " +
                "redis.call('pexpire', KEYS[1], ARGV[2]); " +
                "return 0; " +
            // 否则证明锁已经释放,删除key并发布锁释放的消息
            "else " +
                "redis.call('del', KEYS[1]); " +
                "redis.call('publish', KEYS[2], ARGV[1]); " +
                "return 1; "+
            "end; " +
            "return nil;",
            Arrays.<Object>asList(getName(), getChannelName()), LockPubSub.unlockMessage, internalLockLeaseTime, getLockName(threadId));

}

代码部分

pom依赖

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

其他的辅助util依赖

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.58</version>
</dependency>

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-collections4</artifactId>
    <version>4.3</version>
</dependency>

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.4</version>
</dependency>

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>19.0</version>
</dependency>

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.8</version>
    <scope>provided</scope>
</dependency>

application.properties

redis.config.host=redis://localhost:6379

Redisson配置类

package com.wjx.config;

import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Created by dingguo on 2020/5/15 下午3:47
 */

@Configuration
public class RedisConfig {


    @Value("${redis.config.host}")
    private String address;


    @Bean
    public RedissonClient getRedissonClient() {
        // 创建 Config
        Config config = new Config();
        // 设置为单节点redis
        config.useSingleServer().setAddress(this.address);
        // 通过Redisson创建client实例
        return Redisson.create(config);
    }
}

Service秒杀处理类

package com.wjx.service;

import com.google.common.collect.Lists;
import org.apache.commons.collections4.MapUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by dingguo on 2020/5/15 下午3:53
 * 使用 Redission 分布式锁,实现秒杀商品功能
 */

@Service
public class KillItmsService {


    @Autowired
    private RedissonClient redissonClient;


    /**
     * 模拟多线程每次请求的用户id
     */
    private static List<Integer> userIds;

    /**
     * 初始秒杀商品的库存,实际情况可能存在redis
     */
    private static ConcurrentHashMap<Integer, AtomicInteger> killQuantityMap = new ConcurrentHashMap<>();

    /**
     * 记录秒杀成功的用户,实际情况可能存在redis
     */
    private static ConcurrentHashMap<Integer, Integer> killUserIdMaps = new ConcurrentHashMap<>();

    static {
        userIds = Lists.newArrayList(10001, 10002, 10003, 10004, 10005, 10006, 10007, 10008, 10009, 10010);
        killQuantityMap.put(1001, new AtomicInteger(6));
    }

    /**
     * 秒杀抢商品
     */
    public Boolean killItem(Integer killId) {

        // 随机获取访问的用户,模拟不同用户请求
        int index = new Random().nextInt(9);
        Integer userId = userIds.get(index);

        boolean result = false;

        final String lockKey = String.valueOf(killId) + userId + "-RedissonLock";
        // 加锁
        RLock lock = redissonClient.getLock(lockKey);

        try {
            // TODO: 2020/5/15 第一个参数为 30, 尝试获取锁的的最大等待时间为30s
            // TODO: 2020/5/15 第二个参数为 60,  上锁成功后60s后锁自动失效
            // 尝试获取锁(可重入锁,不会造成死锁)
            boolean lockFlag = lock.tryLock(30, 60, TimeUnit.SECONDS);
            if (lockFlag) {
                // 做幂等性处理
                if (MapUtils.isNotEmpty(killUserIdMaps) && killUserIdMaps.get(userId) != null) {
                    System.err.println("用户:" + userId + "---已抢到商品:" + killId + ",不可以重新领取");
                    return false;
                }

                /*
                 * ***************************************************************
                 *                          处理核心内容
                 * ***************************************************************
                 */
                AtomicInteger quantity = killQuantityMap.get(killId);
                if (quantity.get() > 0) {
                    quantity.decrementAndGet();
                    // TODO: 2020/5/15 killUserIdMaps 实际业务场景,秒杀抢到商品的用户可以存入redis缓存
                    killUserIdMaps.put(userId, killId);
                    // TODO: 2020/5/15 killQuantityMap 实际业务场景,读取数据库或者缓存的商品库存,判断是否被抢完了
                    killQuantityMap.put(killId, quantity);
                    System.out.println("用户:" + userId + "---抢到商品:" + killId);
                } else {
                    System.err.println("用户:" + userId + "---未抢到商品:" + killId);
                }
                result = true;
            } else {
                System.out.println("当前锁资源被占用<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<未获取到锁");
            }
        } catch (Exception e) {
            System.err.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>.出现了错误");
        } finally {
            // 解锁
            lock.unlock();
        }
        return result;
    }

    public void init() {
        killQuantityMap.put(1001, new AtomicInteger(6));
        killUserIdMaps.clear();
    }
}

源码地址,使劲戳戳戳~~~~

参考文章:

可重入锁详解(什么是可重入)_石头StoneWang的博客-CSDN博客_可重入锁

分布式锁之Redis实现 - 简书

  • 3
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 在Spring Boot项目中使用Redisson实现分布式锁,需要按照以下步骤进行: 1. 在项目中引入Redisson依赖,可以在pom.xml文件中添加以下代码: ``` <dependency> <groupId>org.redisson</groupId> <artifactId>redisson</artifactId> <version>3.13.3</version> </dependency> ``` 2. 配置Redisson连接,可以在application.yml文件中添加以下代码: ``` redisson: address: redis://127.0.0.1:6379 database: 0 connection-pool-size: 100 password: 123456 ``` 3. 创建RedissonClient对象,可以在Spring Boot项目的启动类中添加以下代码: ``` @Configuration public class RedissonConfig { @Value("${redisson.address}") private String address; @Value("${redisson.password}") private String password; @Value("${redisson.connection-pool-size}") private int connectionPoolSize; @Value("${redisson.database}") private int database; @Bean public RedissonClient redissonClient() { Config config = new Config(); config.useSingleServer().setAddress(address) .setPassword(password) .setConnectionPoolSize(connectionPoolSize) .setDatabase(database); return Redisson.create(config); } } ``` 4. 使用Redisson实现分布式锁,可以在需要加锁的代码中添加以下代码: ``` @Autowired private RedissonClient redissonClient; public void lockMethod() { RLock lock = redissonClient.getLock("lockKey"); try { lock.lock(); // 被锁定的代码 } finally { lock.unlock(); } } ``` 以上代码就是使用Redisson实现分布式锁的基本过程,实际项目中可能还需要根据实际情况进行修改和优化。 ### 回答2: Spring Boot是一款用于快速构建Spring应用程序的开发框架,而Redisson则是一个基于Redis的Java驻留内存数据网格(In-Memory Data Grid)和分布式锁框架。 在Spring Boot中使用Redisson实现分布式锁,需要进行以下几个步骤: 1. 引入Redisson依赖:在pom.xml文件中添加Redisson的依赖。例如: ```xml <dependency> <groupId>org.redisson</groupId> <artifactId>redisson-spring-boot-starter</artifactId> <version>3.13.3</version> </dependency> ``` 2. 配置Redisson:在application.properties或application.yml文件中配置Redisson连接信息。例如: ```yaml spring: redis: host: 127.0.0.1 port: 6379 password: password ``` 3. 创建RedissonClient Bean:在应用程序的配置类中创建RedissonClient的Bean实例。例如: ```java @Configuration public class RedissonConfig { @Value("${spring.redis.host}") private String host; @Value("${spring.redis.port}") private String port; @Bean public RedissonClient redisson() { Config config = new Config(); config.useSingleServer() .setAddress("redis://" + host + ":" + port); return Redisson.create(config); } } ``` 4. 使用分布式锁:在需要进行分布式锁控制的代码块中,通过RedissonClient来获取分布式锁对象,并使用分布式锁对象来实现具体的业务逻辑。例如: ```java @Service public class MyService { @Autowired private RedissonClient redisson; public void doSomething() { RLock lock = redisson.getLock("myLock"); try { lock.lock(); // 执行业务逻辑 } finally { lock.unlock(); } } } ``` 上述代码中,通过调用`redisson.getLock("myLock")`来获取名为"myLock"的分布式锁对象(RLock),然后通过`lock.lock()`来获取锁,执行业务逻辑,最后通过`lock.unlock()`来释放锁。 这样,Spring Boot就可以通过Redisson实现分布式锁的功能了。分布式锁的主要作用是在分布式系统中保证同一时刻只有一个线程能够访问共享资源,避免数据的冲突和不一致。通过使用Redisson,我们可以方便地在Spring Boot应用中实现分布式锁的控制,保证数据的一致性和可靠性。 ### 回答3: Spring Boot是一个快速开发框架,可以简化Java应用程序的开发过程。而Redisson是一个使用Java实现的Redis客户端,它提供了一种简单易用且高效的分布式锁解决方案。 要使用Redisson实现分布式锁,我们需要完成以下几个步骤: 1. 添加Redisson依赖:首先,在Spring Boot项目的pom.xml文件中添加Redisson的依赖。可以通过在<dependencies>标签内添加如下代码来引入Redisson: ```xml <dependency> <groupId>org.redisson</groupId> <artifactId>redisson-spring-boot-starter</artifactId> <version>3.11.3</version> </dependency> ``` 2. 添加Redis配置信息:在Spring Boot项目的配置文件(如application.properties)中添加Redis的相关配置信息,包括主机名、端口号、密码等。示例配置如下: ```properties spring.redis.host=127.0.0.1 spring.redis.port=6379 spring.redis.password= ``` 3. 创建RedissonClient Bean:在Spring Boot的配置类中创建一个RedissonClient的Bean,并设置好相应的Redis配置信息。示例代码如下: ```java @Configuration public class RedissonConfig { @Value("${spring.redis.host}") private String redisHost; @Value("${spring.redis.port}") private String redisPort; @Bean public RedissonClient redissonClient() { Config config = new Config(); config.useSingleServer().setAddress("redis://" + redisHost + ":" + redisPort); return Redisson.create(config); } } ``` 4. 使用Redisson获取锁:在需要加锁的业务方法中,通过RedissonClient的getFairLock方法获取一个公平锁对象,然后使用lock方法获取锁。示例代码如下: ```java @Service public class MyService { @Autowired private RedissonClient redissonClient; public void doSomething() { RLock lock = redissonClient.getFairLock("myLock"); try { lock.lock(); // 执行需要加锁的业务逻辑 } finally { lock.unlock(); } } } ``` 以上就是使用Spring Boot和Redisson实现分布式锁的基本步骤。通过Redisson提供的锁对象,我们可以在需要时通过lock方法获取锁,然后执行需要加锁的业务逻辑,最后通过unlock方法释放锁。Redisson会自动处理锁的有效期和宕机等异常情况,保证高可用和数据一致性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值