| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117 |
- 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 只是热路径缓存)。
- *
- * <p>键(见设计 §4.5):
- * <ul>
- * <li>{@code gateway:route:user:{serviceId}:{userId} → nodeId}(无 TTL)</li>
- * <li>{@code gateway:route:name:{serviceId}:{lower(username)} → nodeId}(无 TTL)</li>
- * </ul>
- *
- * <p>Redis 读失败降级为直查数据库;缓存写失败只记日志(下次读会回源)。
- * 管理端重绑/解绑在写库后同步清缓存。
- */
- @Slf4j
- @Service
- @RequiredArgsConstructor
- public class UserRouteService {
- private final ReactiveStringRedisTemplate redis;
- private final UserRouteRepository repository;
- public Mono<String> findNodeIdByUserId(String serviceId, long userId) {
- String key = userKey(serviceId, userId);
- return getWithCache(key,
- () -> repository.findNodeIdByUserId(serviceId, userId));
- }
- public Mono<String> 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<String> getWithCache(String key, java.util.function.Supplier<String> dbLookup) {
- Mono<String> 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<String> 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<Void> 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<Void> cacheUser(String serviceId, Long userId, String username, String nodeId) {
- if (nodeId == null) {
- return Mono.empty();
- }
- Mono<Boolean> 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<String> cacheKeys(String serviceId, Long userId, String username) {
- java.util.List<String> 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();
- }
- }
|