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的高效操作和管理。