redis乐观锁实现高并发秒杀

转自:
作者:牡丹男孩
链接:https://www.jianshu.com/p/06f1bce98451

在限量秒杀抢购的场景,一定会遇到抢购成功数超过限量的问题和高并发的情况影响系统性能

1、虽然能用数据库的锁避免,超过限量的问题。但是在大并发的情况下,大大影响数据库性能
2、为了避免并发操作数据库,我们可以使用队列来限制,但是并发量会让队列内存瞬间升高
3、我们又可以用悲观锁来实现,但是这样会造成用户等待,响应慢体验不好

因此我们可以利用redis来实现乐观锁

1、利用redis的watch功能,监控这个redisKey的状态值
2、获取redisKey的值
3、创建redis事务
4、给这个key的值+1
5、然后去执行这个事务,如果key的值被修改过则回滚,key不+1

这里我用java实现,我开20个线程模拟10000个人并发来抢购,其它语言也是一样的实现原理。

package com.kuang;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

import java.util.List;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by zjl
 * 2021/2/18
 **/
public class 秒杀 {
    
    
    public static void main(String[] arg){
    
    
        String redisKey = "redisTest";
        ExecutorService executorService = Executors.newFixedThreadPool(20);
        try {
    
    
            Jedis jedis = new Jedis("127.0.0.1",6379);
            jedis.auth("123456");
            jedis.set(redisKey,"0");
            jedis.close();
        }catch (Exception e){
    
    
            e.printStackTrace();
        }

        for (int i=0;i<10000;i++){
    
    
            executorService.execute(()->{
    
    
                Jedis jedis1 = new Jedis("127.0.0.1",6379);
                jedis1.auth("123456");
                try {
    
    
                    jedis1.watch(redisKey);
                    String redisValue = jedis1.get(redisKey);
                    int valInteger = Integer.valueOf(redisValue);
                    String userInfo = UUID.randomUUID().toString();
                    if (valInteger<20){
    
    
                        Transaction transaction = jedis1.multi();
                        transaction.incr(redisKey);
                        List list = transaction.exec();
                        if (list!=null){
    
    
                            System.out.println("用户:"+userInfo+",秒杀成功!当前成功人数:"+(valInteger+1));
                        }else {
    
    
                            System.out.println("用户:"+userInfo+",秒杀失败");
                        }
                    }else {
    
    
                        System.out.println("已经有20人秒杀成功,秒杀结束");
                    }
                }catch (Exception e){
    
    
                    e.printStackTrace();
                }finally {
    
    
                    jedis1.close();
                }
            });
        }
        executorService.shutdown();
    }
}

在这里插入图片描述
如果有什么不对的地方请积极指出!

猜你喜欢

转载自blog.csdn.net/qq_41347385/article/details/113851822