分布式锁实现----Mysql

使用场景:项目并发很低的时候可以用

Mysql锁的实现:

通过ThreadLocal进行参数传递

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
@Service
@Data
public class MysqlLock implements Lock {

@Autowired
private TblOrderLockDao mapper;

private ThreadLocal<TblOrderLock> orderLockThreadLocal ;

@Override
public void lock() {
// 1、尝试加锁
if(tryLock()) {
System.out.println("尝试加锁");
return;
}
// 2.休眠
try {
Thread.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 3.递归再次调用
lock();
}

/**
* 非阻塞式加锁,成功,就成功,失败就失败。直接返回
*/
@Override
public boolean tryLock() {
try {
TblOrderLock tblOrderLock = orderLockThreadLocal.get();
mapper.insertSelective(tblOrderLock);
System.out.println("加锁对象:"+orderLockThreadLocal.get());
return true;
}catch (Exception e) {
return false;
}
}
@Override
public void unlock() {
mapper.deleteByPrimaryKey(orderLockThreadLocal.get().getOrderId());
System.out.println("解锁对象:"+orderLockThreadLocal.get());
orderLockThreadLocal.remove();
}
}

业务逻辑

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
public class GrabMysqlLockServiceImpl implements GrabService{
@Autowired
private MysqlLock lock;
@Autowired
OrderService orderService;
ThreadLocal<TblOrderLock> orderLock = new ThreadLocal<>();
@Override
public String grabOrder(int orderId, int driverId) {
//生成 锁
//生成key
TblOrderLock ol = new TblOrderLock();
ol.setOrderId(orderId);
ol.setDriverId(driverId);

orderLock.set(ol);
lock.setOrderLockThreadLocal(orderLock);

// lock ----------
lock.lock();

//执行业务
try{
System.out.println("司机:"+driverId+" 执行抢单逻辑");
boolean b = orderService.grab(orderId, driverId);
if(b) {
System.out.println("司机:"+driverId+" 抢单成功");
}else{
System.out.println("司机:"+driverId+" 抢单失败");
}
}finally{
//释放锁
lock.unlock();
}
return null;
}
}

分布式锁实现----Mysql
http://yoursite.com/post/d8430ae1.html/
Author
Chase Wang
Posted on
November 25, 2021
Licensed under