1、Maven依赖
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson</artifactId>
<version>3.13.0</version>
</dependency>
2、application.yml添加配置
# 分布式锁
redisson:
signle:
timeout: 30000
address: redis://127.0.0.1:6379
password: dev-foo
database: 10
connectionPoolSize: 50
connectionMinimumIdleSize: 10
3、RedissonAutoConfiguration 配置类
import lombok.Data;
import org.apache.commons.lang.StringUtils;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Data
@Configuration
@ConditionalOnClass(Config.class)
@EnableCaching
@ConfigurationProperties(prefix = "redisson.signle")
public class RedissonAutoConfiguration {
private int timeout;
private String address;
private String password;
private int database;
private int connectionPoolSize;
private int connectionMinimumIdleSize;
/**
* 单机模式自动装配
*
* @return
*/
@Bean
public RedissonClient redissonClient() {
Config config = new Config();
SingleServerConfig serverConfig = config.useSingleServer()
.setDatabase(database)
.setAddress(address)
.setTimeout(timeout)
.setConnectionPoolSize(connectionPoolSize)
.setConnectionMinimumIdleSize(connectionMinimumIdleSize);
if (StringUtils.isNotBlank(password)) {
serverConfig.setPassword(password);
}
return Redisson.create(config);
}
}
4、业务代码
@Resource
private RedissonClient redissonClient;
public void method1(){
RLock lock = redissonClient.getLock(锁住的对象);
try{
// 第一种,加锁 锁的有效期默认30秒
lock.lock();
// 第二种,可重入锁,如果三个线程同时竞争,一个线程执行完会给到下个线程
lock.lock(5, TimeUnit.SECONDS); //过期锁时间5秒
// 第三种,尝试加锁,最多等待1秒,如果超时还获取不到锁就返回false,上锁以后10秒自动解锁
boolean res = lock.tryLock(1, 10, TimeUnit.SECONDS)
// 业务代码
}catch() {
log.error();
}finally{
if (lock.isLocked()) {
lock.unlock();
} else {
log.debug("已经释放锁了");
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/71378.html