一、通过maven引入redisson的jar包
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson</artifactId>
<version>3.6.5</version>
</dependency>
二、在yaml文件中引入redis的相关配置(redis单节点可以读取原有redis配置拼装,如果是主从需另外独立配置,相关属性可以参考org.redisson.config.Config.masterSlaveServersConfig)
spring:
redis:
host: 127.0.0.1
port: 6379
password: 111111
三、添加springboot配置
package com.aoxun.config;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* redisson配置
* 目前使用的是腾讯云的单节点redis,所以暂时配置单服务
*
*
*/
@Configuration
public class RedissonConfig {
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.port}")
private String port;
@Value("${spring.redis.password}")
private String password;
@Bean
public RedissonClient getRedisson(){
Config config = new Config();
config.useSingleServer().setAddress("redis://" + host + ":" + port).setPassword(password);
//添加主从配置
// config.useMasterSlaveServers().setMasterAddress("").setPassword("").addSlaveAddress(new String[]{"",""});
return Redisson.create(config);
}
}
四、在需要使用的地方注入RedissonClient即可
package com.aoxun.modular.menjin.service.impl;
import java.util.concurrent.TimeUnit;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class TestRedissonLock{
@Autowired
private RedissonClient redissonClient;
public void cameraCallback() {
RLock rlock = redissonClient.getLock("redisson:lock:personId" + 123); //设置锁超时时间,防止异常造成死锁
rlock.lock(20, TimeUnit.SECONDS);
try{
//执行业务逻辑
Thread.sleep(10000);
System.out.println(123);
} catch(Exception e){
}finally{
rlock.unlock();
}
}
}
到此利用redisson实现分布式锁简单样例已经结束