|
7 i) P% l; j7 U/ h+ X& ?
- public boolean acquire(String lockName) {
5 D" D7 z. L/ q' N/ [6 n - //声明key对象
6 P5 l4 O2 S2 D# s - String key = LOCK_TITLE + lockName;+ ~# @* u8 }( g
- //获取锁对象
) L; e+ w- M$ u* k& Q. W+ G - RLock mylock = redissonClient.getLock(key);/ Z6 H P8 _/ k+ v! p" p
- //加锁,并且设置锁过期时间3秒,防止死锁的产生 uuid+threadId6 Y1 x( k m8 {* J+ r& |
- mylock.lock(3, TimeUnit.SECONDS);! @# J& n0 d" c2 _1 e) D
- //加锁成功
1 }- a: o; f, p! t' | - return true;' `; s) x& J3 k }. g# e. @! ?
- }" ^% q3 L5 q5 L F5 u& h0 E
8 A$ Q- \$ ?3 [* V" `+ F- public void release(String lockName) {
% i1 u1 {( f5 V- J4 @9 Q# `! G - String key = LOCK_TITLE + lockName;
5 m m; I* `, c - RLock mylock = redissonClient.getLock(key);: U1 K% s5 G4 F7 N3 x0 \7 h0 K0 [
- mylock.unlock();( G9 t0 [6 s3 f n T8 [* `
- }; t8 i* w0 c5 q! j% L9 ~
调用如下7 J6 F4 w1 |1 m6 T. i% R, x
* B1 p! H5 @2 w# `+ w$ [- boolean acquire = distributedRedisLock.acquire(CacheKey.REGISTER_SMS_RECALL);
?+ N1 h* `) V1 O - try { J# D$ ^% p, |" N: a @; c* U% T
- if (acquire) {4 a* o, R# E* A [4 ^
- taskExecutor.execute(() -> {
5 C! L3 I" U, P5 z- M6 j- |- K - log.info("多线程测试");; g. q, R1 W1 v( f1 g% b
- });1 n8 |2 Y+ b! J8 a* J* B4 |
- }
; E$ H$ v- p3 l+ j+ R' p - }catch (Exception e) {
/ f+ |+ J, c( [' k3 u2 { - log.info("{}", ExceptionUtils.getFullStackTrace(e));; j! R3 {6 B& Z- r. }
- }finally {
" h) L' x- S" b" N - distributedRedisLock.release(CacheKey.REGISTER_SMS_RECALL); }
# q8 T0 e& ], @ 上锁方法如上,但是使用多线程调用的时候,上锁失败了
. w( [/ n( _' p4 N- Application_Stdout [2021-12-29 11:06:52] [traceid=yPGwkuNz,uid=,uri=/mid/test/test,host=192.168.126.47,ref=,ua=python-requests/2.26.0] INFO [http-nio-8089-exec-6] o.n.mid.task.SmsRecallRegisterTask[48] - 多线程测试: m! g; ~, M7 j; M* f
- Application_Stdout [2021-12-29 11:06:52] [traceid=krfsFsWv,uid=,uri=/mid/test/test,host=192.168.126.47,ref=,ua=python-requests/2.26.0] INFO [http-nio-8089-exec-8] o.n.mid.task.SmsRecallRegisterTask[48] - 多线程测试Application_Stdout [2021-12-29 11:06:52] [traceid=8c9RU1WK,uid=,uri=/mid/test/test,host=192.168.126.47,ref=,ua=python-requests/2.26.0] INFO [http-nio-8089-exec-10] o.n.mid.task.SmsRecallRegisterTask[48] - 多线程测试3 |/ d7 U, o# c5 G4 _4 g
- q: i7 }* N9 v4 M- z
$ G r0 n' G8 V我知道答案 回答被采纳将会获得5 金钱 已有0人回答 |
|