分布式锁实现主流的三中方式:
1、数据库实现
2、zk实现、
3、基于redisson实现redis分布式锁
话不多说直接上代码:
pom.xml文件中添加以下依赖:
<!-- Redisson 实现分布式锁 -->
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson</artifactId>
<version>3.8.2</version>
</dependency>
添加RedisConfigProperties 类,
package com.guava.guava.distributedlock.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
@ConfigurationProperties(prefix = "spring.redis")
public class RedisConfigProperties {
private String password;
private cluster cluster;
public static class cluster {
private List<String> nodes;
public List<String> getNodes() {
return nodes;
}
public void setNodes(List<String> nodes) {
this.nodes = nodes;
}
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public RedisConfigProperties.cluster getCluster() {
return cluster;
}
public void setCluster(RedisConfigProperties.cluster cluster) {
this.cluster = cluster;
}
}
RedissonClient 创建,该项目是基于redis集群模式实现的
package com.guava.guava.distributedlock.config;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.ClusterServersConfig;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.ArrayList;
import java.util.List;
@Configuration
public class RedisConfig {
/* @Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.port}")
private String port;
@Value("${spring.redis.password}")
private String password;
*/
@Autowired
private RedisConfigProperties redisConfigProperties;
//rediss单机模式
/*@Bean
public RedissonClient singleRedisson(){
Config config = new Config();
config.useSingleServer().setAddress("redis://" + host + ":" + port);
if (!password.isEmpty()) {
config.useSingleServer().setPassword(password);
}
return Redisson.create(config);
}*/
//rediss集群模式
@Bean
public RedissonClient redisson() {
//redisson版本是3.5,集群的ip前面要加上“redis://”,不然会报错,3.2版本可不加
List<String> clusterNodes = new ArrayList<>();
for (int i = 0; i < redisConfigProperties.getCluster().getNodes().size(); i++) {
clusterNodes.add("redis://" + redisConfigProperties.getCluster().getNodes().get(i));
}
Config config = new Config();
ClusterServersConfig clusterServersConfig = config.useClusterServers()
.addNodeAddress(clusterNodes.toArray(new String[clusterNodes.size()]));
if (!redisConfigProperties.getPassword().isEmpty()) {
clusterServersConfig.setPassword(redisConfigProperties.getPassword());//设置密码
}
return Redisson.create(config);
}
}
application.properties添加redis相关配置信息
# redis
#spring.redis.host=10.25.23.160
spring.redis.cluster.nodes=10.**.23.***:6379,10.**.23.***:6379,10.**.23.***:6379,10.**.23.***:6379,10.**.23.***:6379,10.**.23.***:6379
#spring.redis.port=6379
spring.redis.password=
spring.redis.jedis.pool.max-active=500
spring.redis.jedis.pool.max-idle=1000
spring.redis.jedis.pool.max-wait=6000ms
spring.redis.jedis.pool.min-idle=4
#zk
redis分布式锁API接口
package com.guava.guava.distributedlock.redis;
import java.util.concurrent.TimeUnit;
public interface RedisLock {
void lock(String lockKey);
void relaseLock(String lockKey);
void lock(String lockKey, int timeOut);
void lock(String lockKey, TimeUnit unit, int timeout);
boolean tryLock(String lockKey);
boolean tryLock(String lockKey, long waitTime, long leaseTime, TimeUnit unit)
throws InterruptedException;
boolean isLocked(String lockKey);
}
redis分布式锁API接口实现类
package com.guava.guava.distributedlock.redis;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;
@Service
public class RedisLockImpl implements RedisLock {
private static final Logger LOGGER = LoggerFactory.getLogger(RedisLockImpl.class);
@Autowired
private RedissonClient redissonClient;
public RedisLockImpl(RedissonClient redissonClient) {
this.redissonClient = redissonClient;
}
@Override
public void lock(String lockKey) {
RLock lock = redissonClient.getLock(lockKey);
lock.lock();
}
@Override
public void relaseLock(String lockKey) {
RLock rLock = redissonClient.getLock(lockKey);
rLock.unlock();
}
@Override
public void lock(String lockKey, int timeOut) {
RLock rLock = redissonClient.getLock(lockKey);
rLock.lock(timeOut,TimeUnit.SECONDS);
}
@Override
public void lock(String lockKey, TimeUnit unit, int timeout) {
RLock rLock = redissonClient.getLock(lockKey);
rLock.lock(timeout, unit);
}
@Override
public boolean tryLock(String lockKey) {
RLock rLock = redissonClient.getLock(lockKey);
return rLock.tryLock();
}
@Override
public boolean tryLock(String lockKey, long waitTime, long leaseTime, TimeUnit unit) throws InterruptedException {
RLock rLock = redissonClient.getLock(lockKey);
return rLock.tryLock(waitTime,leaseTime,unit);
}
@Override
public boolean isLocked(String lockKey) {
RLock rLock = redissonClient.getLock(lockKey);
return rLock.isLocked();
}
}
接下来做测试即可。
网友评论