分布式锁
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;
}
}
首先不是使用锁的情况
-
JMeter模拟并发
image.png
恭喜活动购买权利!!
商品库存剩余: 29
恭喜活动购买权利!!
商品库存剩余: 29
恭喜活动购买权利!!
商品库存剩余: 29
恭喜活动购买权利!!
商品库存剩余: 28
...
- 如果加上synchronized呢 看效果
恭喜活动购买权利!!
商品库存剩余: 29
恭喜活动购买权利!!
商品库存剩余: 28
恭喜活动购买权利!!
商品库存剩余: 27
恭喜活动购买权利!!
商品库存剩余: 26
恭喜活动购买权利!!
商品库存剩余: 25
恭喜活动购买权利!!
商品库存剩余: 24
恭喜活动购买权利!!
商品库存剩余: 23
恭喜活动购买权利!!
...
确实是按照预期的执行了,注意这是单机,现在模拟集群
模拟集群并发
- 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
- IDEA启动多个Spring Boot工程实例
- 在IDEA上点击Application右边的下三角
,弹出选项后,点击Edit Configuration
-
step 2
打开配置后,将默认的Single instance only(单实例)的钩去掉。
image.png
- step 3
通过修改application文件的server.port的端口,启动。多个实例,需要多个端口,分别启动。 -
启动第一个
image.png - 修改端口号启动第二个
模拟并发
8090 端口
image.png
8080 端口
image.png