分布式锁

2020-08-26  本文已影响0人  wanggs

SpringBoot 分布式锁

模拟秒杀代码片段

控制器
package com.wanggs.seckill.controller;

import com.wanggs.seckill.service.SKService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author Wgs
 * @version 1.0
 * @create:2019/05/28
 */
@RestController
public class SeckillController {
    @Resource
    private SKService skService = null;
    @GetMapping("/kill")
    public String kill(){
        skService.processSeckill();
        return "ok";
    }
}


service
package com.wanggs.seckill.service;

import com.wanggs.seckill.dao.SKDao;
import org.springframework.stereotype.Service;

/**
 * @author Wgs
 * @version 1.0
 * @create:2019/05/28
 */
@Service
public class SKService {
    SKDao skDao = new SKDao();

    public synchronized  void processSeckill(){
        int count = skDao.getCount();
        if (count > 0){
            System.out.println("恭喜活动购买权利!!");
            count = count -1;
            System.out.println("商品库存剩余: "+count);
            skDao.updateCount(count);
        }else {
            System.out.println("商品购买完了");
        }
    }
}

dao
package com.wanggs.seckill.dao;

/**
 * @author Wgs
 * @version 1.0
 * @create:2019/05/28
 */
public class SKDao {
    public static Integer count = 30;

    public Integer getCount(){
        return SKDao.count;
    }

    public void updateCount(Integer count){
        SKDao.count =count;

    }
}

首先不是使用锁的情况

  1. JMeter模拟并发


    image.png
恭喜活动购买权利!!
商品库存剩余: 29
恭喜活动购买权利!!
商品库存剩余: 29
恭喜活动购买权利!!
商品库存剩余: 29
恭喜活动购买权利!!
商品库存剩余: 28
...
  1. 如果加上synchronized呢 看效果
恭喜活动购买权利!!
商品库存剩余: 29
恭喜活动购买权利!!
商品库存剩余: 28
恭喜活动购买权利!!
商品库存剩余: 27
恭喜活动购买权利!!
商品库存剩余: 26
恭喜活动购买权利!!
商品库存剩余: 25
恭喜活动购买权利!!
商品库存剩余: 24
恭喜活动购买权利!!
商品库存剩余: 23
恭喜活动购买权利!!
...

确实是按照预期的执行了,注意这是单机,现在模拟集群

模拟集群并发
  1. nginx配置
    upstream lc { 
      server 127.0.0.1:8080; 
      server 127.0.0.1:8090; 
}

    server {
        listen       80;
        server_name  localhost;

        location / {
            root   html;
            index  index.html index.htm;
            # proxy_pass http://rr; 
              proxy_pass http://lc; 
        }

image.png
  1. IDEA启动多个Spring Boot工程实例
image.png

模拟并发

8090 端口


image.png

8080 端口


image.png
明显有问题,synchronized 是基于jvm的,8080端口购买过,8090就不应该重复购买

使用redis解决

上一篇下一篇

猜你喜欢

热点阅读