RedisLock.java
931 Bytes
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
package cn.com.glsx.entmicro.config;/**
* @author zhouhaibao
* @date 2021/10/21
*/
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;
/**
* @author zhouhaibao
* @version 1.0
* @description: redis分布式锁
* @date 2021/10/21 17:53
*/
@Component
public class RedisLock {
@Autowired
private RedisTemplate redisTemplate;
/**
* 获得锁
*/
public boolean getLock(String lockId, long millisecond) {
Boolean success = redisTemplate.opsForValue().setIfAbsent(lockId, "lock",
millisecond, TimeUnit.MILLISECONDS);
return success != null && success;
}
/**
* 释放锁
*
* @param lockId
*/
public void releaseLock(String lockId) {
redisTemplate.delete(lockId);
}
}