Redisson 分布式组件
约 730 字大约 2 分钟
布欧-Lewyon
2026-05-15
Redisson 是 Java 的 Redis 客户端,提供分布式锁、分布式集合、限流器等高阶数据结构。
依赖与配置
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson-spring-boot-starter</artifactId>
<version>3.37.0</version>
</dependency>spring:
data:
redis:
host: localhost
port: 6379
# 或
redisson:
config: |
singleServerConfig:
address: "redis://localhost:6379"
password: null@Configuration
public class RedissonConfig {
@Bean
public RedissonClient redissonClient() {
Config config = new Config();
config.useSingleServer()
.setAddress("redis://localhost:6379")
.setPassword(null)
.setConnectionPoolSize(50)
.setConnectionMinimumIdleSize(10);
return Redisson.create(config);
}
}分布式锁
@Service
public class DistributedLockService {
@Autowired
private RedissonClient redissonClient;
public void processOrder(Long orderId) {
String lockKey = "lock:order:" + orderId;
RLock lock = redissonClient.getLock(lockKey);
try {
// 尝试加锁,最多等 5 秒,锁有效期 30 秒
if (lock.tryLock(5, 30, TimeUnit.SECONDS)) {
try {
// 业务逻辑
processPayment(orderId);
} finally {
lock.unlock();
}
} else {
throw new RuntimeException("系统繁忙,请稍后重试");
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
// 看门狗模式:自动续期(默认 30 秒,业务没执行完自动续)
public void withWatchDog(Long orderId) {
RLock lock = redissonClient.getLock("lock:order:" + orderId);
lock.lock(); // 看门狗自动续期
try {
processPayment(orderId);
} finally {
lock.unlock();
}
}
}可重入锁
// Redisson 分布式锁默认可重入
RLock lock = redissonClient.getLock("lock:key");
lock.lock(); // 第 1 次获取
lock.lock(); // 第 2 次获取(可重入)
lock.unlock(); // 释放 1 次
lock.unlock(); // 释放 2 次读写锁
RReadWriteLock rwLock = redissonClient.getReadWriteLock("rw:lock");
RLock readLock = rwLock.readLock();
RLock writeLock = rwLock.writeLock();
// 读锁:可多个同时读
readLock.lock();
try { readData(); } finally { readLock.unlock(); }
// 写锁:独占
writeLock.lock();
try { writeData(); } finally { writeLock.unlock(); }分布式限流器
@Service
public class RateLimiterService {
@Autowired
private RedissonClient redissonClient;
// 接口限流:每分钟不超过 10 次
public boolean tryAcquire(String userId) {
RRateLimiter limiter = redissonClient.getRateLimiter("rate:api:" + userId);
// 初始化:每分钟 10 个令牌
limiter.trySetRate(RateType.OVERALL, 10, 1, RateIntervalUnit.MINUTES);
return limiter.tryAcquire();
}
// 网关级别限流
public boolean gatewayAcquire() {
RRateLimiter limiter = redissonClient.getRateLimiter("rate:gateway");
limiter.trySetRate(RateType.OVERALL, 1000, 1, RateIntervalUnit.SECONDS);
return limiter.tryAcquire();
}
}分布式集合
@Service
public class DistributedCollectionService {
@Autowired
private RedissonClient redisson;
// RMap(分布式 Map)
public void mapOps() {
RMap<String, String> map = redisson.getMap("user:100");
map.put("name", "Alice");
map.put("age", "25");
String name = map.get("name");
// 本地缓存(每个节点缓存一部分,减少网络开销)
RLocalCachedMap<String, String> cached = redisson.getLocalCachedMap("cache",
LocalCachedMapOptions.defaults());
}
// RList
public void listOps() {
RList<String> list = redisson.getList("queue");
list.add("task1");
list.remove("task1");
}
// RScoredSortedSet
public void zSetOps() {
RScoredSortedSet<String> set = redisson.getScoredSortedSet("ranking");
set.add(100, "Alice");
set.add(85, "Bob");
Collection<String> top = set.valueRangeReversed(0, 9);
}
}Spring Cache 整合
@Configuration
@EnableCaching
public class CacheConfig {
@Bean
public RedisCacheManager cacheManager(RedissonClient redissonClient) {
Map<String, CacheConfig> config = new HashMap<>();
config.put("users", new CacheConfig(60 * 1000, 30 * 1000)); // 60s TTL
config.put("products", new CacheConfig(300 * 1000, 60 * 1000));
return new RedissonSpringCacheManager(redissonClient, config);
}
}
// 使用
@Service
public class UserService {
@Cacheable(value = "users", key = "#userId")
public User getUser(Long userId) {
return userRepository.findById(userId); // 只查一次
}
@CacheEvict(value = "users", key = "#userId")
public void updateUser(Long userId) {
userRepository.update(userId);
}
}小结
| 组件 | 用途 |
|---|---|
RLock | 分布式锁(可重入、看门狗自动续期) |
RReadWriteLock | 分布式读写锁 |
RRateLimiter | 分布式限流器(令牌桶) |
RMap / RList / RScoredSortedSet | 分布式集合 |
RedissonSpringCacheManager | Spring Cache 整合 |
- 分布式锁推荐 Redisson,自动续期(看门狗)防止死锁。
- 限流器支持 OVERALL(全局)和 PER_CLIENT(按客户端)模式。
- Spring Cache 注解
@Cacheable直接使用 Redisson。 - Redisson 是 Java 生态中 Redis 分布式组件的首选。
上一节:Spring Boot RedisTemplate 下一节:分布式缓存
