Redission分布式锁
一、引jar包
<!--redisson-->
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson-spring-boot-starter</artifactId>
<version>3.10.6</version>
</dependency>
二、写配置
import org.redisson.Redisson;
import org.redisson.config.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RedissonConfig {
@Bean
public Redisson redisson(){
Config config = new Config();
config.useSingleServer()
.setAddress("redis://192.168.72.111:6379")
.setDatabase(0);
return (Redisson) Redisson.create();
}
}
三、测试使用
@Autowired
private Redisson redisson;
@GetMapping("/hello")
public String r(){
RLock lock = null;
try {
//获取锁,如果锁被占用,会一直循环查看锁可以被使用
lock = redisson.getLock("primary key");
//设置超时时间
lock.lock(20, TimeUnit.SECONDS);
System.out.println("加锁");
/**
* 业务代码
*/
}finally {
lock.unlock();
System.out.println("释放锁!");
}
return "测试成功!";
}
标签:Redisson,lock,redisson,简单,org,import,Config,分布式
From: https://www.cnblogs.com/WangJingjun/p/16652179.html