package com.zsjz.gateway.route;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.ReactiveStringRedisTemplate;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;
import java.time.Duration;
/**
* 用户路由的读写 + Redis 两级缓存(PostgreSQL 是事实来源,Redis 只是热路径缓存)。
*
*
键(见设计 §4.5):
*
* - {@code gateway:route:user:{serviceId}:{userId} → nodeId}(无 TTL)
* - {@code gateway:route:name:{serviceId}:{lower(username)} → nodeId}(无 TTL)
*
*
* Redis 读失败降级为直查数据库;缓存写失败只记日志(下次读会回源)。
* 管理端重绑/解绑在写库后同步清缓存。
*/
@Slf4j
@Service
@RequiredArgsConstructor
public class UserRouteService {
private final ReactiveStringRedisTemplate redis;
private final UserRouteRepository repository;
public Mono findNodeIdByUserId(String serviceId, long userId) {
String key = userKey(serviceId, userId);
return getWithCache(key,
() -> repository.findNodeIdByUserId(serviceId, userId));
}
public Mono findNodeIdByUsername(String serviceId, String username) {
if (username == null || username.isBlank()) {
return Mono.empty();
}
String key = nameKey(serviceId, username);
return getWithCache(key,
() -> repository.findNodeIdByUsername(serviceId, username));
}
private Mono getWithCache(String key, java.util.function.Supplier dbLookup) {
Mono fromCache = redis.opsForValue().get(key)
.onErrorResume(ex -> {
log.info("路由缓存读取失败,回源数据库:{}", ex.toString());
return Mono.empty();
});
return fromCache.switchIfEmpty(Mono.defer(() ->
Mono.fromCallable(dbLookup::get)
.subscribeOn(Schedulers.boundedElastic()))
.flatMap(nodeId -> redis.opsForValue().set(key, nodeId)
.onErrorResume(ex -> {
log.info("路由缓存写入失败(不影响正确性):{}", ex.toString());
return Mono.empty();
})
.thenReturn(nodeId)));
}
/**
* 首次登录成功 / 存量用户兜底绑定:数据库唯一索引裁决并发,返回生效节点。
*/
public Mono bindIfAbsent(String serviceId, Long userId, String username, String nodeId) {
return Mono.fromCallable(() -> repository.bindIfAbsent(serviceId, userId, username, nodeId))
.subscribeOn(Schedulers.boundedElastic())
.flatMap(effective -> cacheUser(serviceId, userId, username, effective).thenReturn(effective));
}
/** 管理端重绑/解绑后清缓存(userId / username 任意一个非空即清对应键) */
public Mono evictUserCache(String serviceId, Long userId, String username) {
return redis.delete(cacheKeys(serviceId, userId, username).toArray(new String[0]))
.onErrorResume(ex -> {
log.info("路由缓存清理失败:{}", ex.toString());
return Mono.just(0L);
})
.then();
}
private Mono cacheUser(String serviceId, Long userId, String username, String nodeId) {
if (nodeId == null) {
return Mono.empty();
}
Mono writes = Mono.just(true);
for (String key : cacheKeys(serviceId, userId, username)) {
writes = writes.flatMap(ignored -> redis.opsForValue().set(key, nodeId));
}
return writes
.onErrorResume(ex -> {
log.info("路由缓存写入失败(不影响正确性):{}", ex.toString());
return Mono.just(false);
})
.then();
}
private java.util.List cacheKeys(String serviceId, Long userId, String username) {
java.util.List keys = new java.util.ArrayList<>(2);
if (userId != null) {
keys.add(userKey(serviceId, userId));
}
if (username != null && !username.isBlank()) {
keys.add(nameKey(serviceId, username));
}
return keys;
}
static String userKey(String serviceId, long userId) {
return "gateway:route:user:" + serviceId + ":" + userId;
}
static String nameKey(String serviceId, String username) {
return "gateway:route:name:" + serviceId + ":" + username.toLowerCase();
}
}