SpringBoot使用Redisson的最佳实践包括以下几点:
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson</artifactId>
<version>3.16.3</version>
</dependency>
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=yourpassword
@Configuration
public class RedissonConfig {
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.port}")
private int port;
@Value("${spring.redis.password}")
private String password;
@Bean
public RedissonClient redissonClient() {
Config config = new Config();
config.useSingleServer()
.setAddress("redis://" + host + ":" + port)
.setPassword(password);
return Redisson.create(config);
}
}
@Autowired
private RedissonClient redissonClient;
public void acquireLock() {
RLock lock = redissonClient.getLock("mylock");
lock.lock();
try {
// do something
} finally {
lock.unlock();
}
}
@PreDestroy
public void close() {
redissonClient.shutdown();
}
通过以上最佳实践,可以更好地集成Redisson到SpringBoot项目中,实现对Redis的高效操作和管理。