refactor(接口命名): 统一接口命名规范并重构相关实现

将接口命名统一调整为以I开头,并重构相关实现类和服务调用
重构审计日志和网关路由服务接口,优化代码结构
删除旧接口文件,更新依赖接口的类
This commit is contained in:
张翔
2026-04-14 18:46:44 +08:00
parent 7e54d7fb46
commit fdca179d45
19 changed files with 757 additions and 565 deletions
@@ -1,223 +0,0 @@
package cn.novalon.manage.gateway.discovery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.discovery.ReactiveDiscoveryClient;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
/**
* 服务发现服务
*
* 文件定义:实现服务实例的发现、监控和管理
* 涉及业务:服务实例查询、健康检查、服务状态监控
*
* 核心功能:
* 1. 服务实例查询
* 2. 服务健康检查
* 3. 服务状态监控
* 4. 服务实例缓存
*
* @author 张翔
* @date 2026-03-26
*/
@Service
public class ServiceDiscoveryService {
private static final Logger logger = LoggerFactory.getLogger(ServiceDiscoveryService.class);
private final ReactiveDiscoveryClient reactiveDiscoveryClient;
private final DiscoveryClient discoveryClient;
private final Map<String, List<ServiceInstance>> serviceCache = new ConcurrentHashMap<>();
private final Map<String, Long> lastUpdateTime = new ConcurrentHashMap<>();
private static final long CACHE_TTL_MS = 30000;
public ServiceDiscoveryService(
ReactiveDiscoveryClient reactiveDiscoveryClient,
DiscoveryClient discoveryClient) {
this.reactiveDiscoveryClient = reactiveDiscoveryClient;
this.discoveryClient = discoveryClient;
initializeServiceCache();
}
private void initializeServiceCache() {
logger.info("Initializing service cache");
discoveryClient.getServices().forEach(serviceId -> {
List<ServiceInstance> instances = discoveryClient.getInstances(serviceId);
if (!instances.isEmpty()) {
serviceCache.put(serviceId, instances);
lastUpdateTime.put(serviceId, System.currentTimeMillis());
logger.debug("Cached {} instances for service: {}", instances.size(), serviceId);
}
});
logger.info("Service cache initialized with {} services", serviceCache.size());
}
public Flux<ServiceInstance> getInstances(String serviceId) {
if (serviceId == null || serviceId.isEmpty()) {
logger.warn("Service ID is null or empty");
return Flux.empty();
}
if (isCacheValid(serviceId)) {
List<ServiceInstance> cachedInstances = serviceCache.get(serviceId);
if (cachedInstances != null && !cachedInstances.isEmpty()) {
logger.debug("Returning {} cached instances for service: {}",
cachedInstances.size(), serviceId);
return Flux.fromIterable(cachedInstances);
}
}
logger.debug("Fetching instances for service: {}", serviceId);
return reactiveDiscoveryClient.getInstances(serviceId)
.doOnNext(instance -> logger.debug("Found instance: {}:{} for service: {}",
instance.getHost(), instance.getPort(), serviceId))
.collectList()
.doOnNext(instances -> {
serviceCache.put(serviceId, instances);
lastUpdateTime.put(serviceId, System.currentTimeMillis());
logger.info("Updated cache with {} instances for service: {}",
instances.size(), serviceId);
})
.flatMapMany(Flux::fromIterable);
}
public Flux<String> getServices() {
return reactiveDiscoveryClient.getServices()
.doOnNext(serviceId -> logger.debug("Found service: {}", serviceId));
}
public Mono<ServiceInstance> getFirstInstance(String serviceId) {
return getInstances(serviceId)
.next()
.doOnNext(instance -> logger.debug("Returning first instance for service: {}", serviceId));
}
public Mono<ServiceInstance> getInstanceByHost(String serviceId, String host) {
if (host == null || host.isEmpty()) {
logger.warn("Host is null or empty");
return Mono.empty();
}
return getInstances(serviceId)
.filter(instance -> host.equals(instance.getHost()))
.next()
.doOnNext(instance -> logger.debug("Found instance with host {} for service: {}",
host, serviceId));
}
public Mono<ServiceInstance> getInstanceByPort(String serviceId, int port) {
if (port <= 0) {
logger.warn("Invalid port: {}", port);
return Mono.empty();
}
return getInstances(serviceId)
.filter(instance -> port == instance.getPort())
.next()
.doOnNext(instance -> logger.debug("Found instance with port {} for service: {}",
port, serviceId));
}
public Mono<Map<String, List<ServiceInstance>>> getAllServicesWithInstances() {
return getServices()
.flatMap(serviceId ->
getInstances(serviceId)
.collectList()
.map(instances -> Map.entry(serviceId, instances))
)
.collectMap(Map.Entry::getKey, Map.Entry::getValue);
}
public Mono<Integer> getInstanceCount(String serviceId) {
return getInstances(serviceId)
.count()
.map(Long::intValue);
}
public Mono<Boolean> isServiceAvailable(String serviceId) {
return getInstanceCount(serviceId)
.map(count -> count > 0)
.doOnNext(available -> logger.debug("Service {} availability: {}",
serviceId, available));
}
public void refreshServiceCache(String serviceId) {
if (serviceId == null || serviceId.isEmpty()) {
logger.warn("Service ID is null or empty");
return;
}
logger.info("Refreshing cache for service: {}", serviceId);
reactiveDiscoveryClient.getInstances(serviceId)
.collectList()
.subscribe(
instances -> {
serviceCache.put(serviceId, instances);
lastUpdateTime.put(serviceId, System.currentTimeMillis());
logger.info("Refreshed cache with {} instances for service: {}",
instances.size(), serviceId);
},
error -> logger.error("Failed to refresh cache for service: {}",
serviceId, error)
);
}
public void refreshAllServices() {
logger.info("Refreshing cache for all services");
reactiveDiscoveryClient.getServices()
.flatMap(serviceId ->
reactiveDiscoveryClient.getInstances(serviceId)
.collectList()
.doOnNext(instances -> {
serviceCache.put(serviceId, instances);
lastUpdateTime.put(serviceId, System.currentTimeMillis());
})
)
.subscribe(
instances -> logger.debug("Refreshed {} instances", instances.size()),
error -> logger.error("Failed to refresh all services", error),
() -> logger.info("All services cache refreshed")
);
}
public void clearServiceCache() {
logger.info("Clearing service cache");
serviceCache.clear();
lastUpdateTime.clear();
initializeServiceCache();
}
private boolean isCacheValid(String serviceId) {
Long lastUpdate = lastUpdateTime.get(serviceId);
if (lastUpdate == null) {
return false;
}
long currentTime = System.currentTimeMillis();
return (currentTime - lastUpdate) < CACHE_TTL_MS;
}
public int getCachedServiceCount() {
return serviceCache.size();
}
public int getCachedInstanceCount(String serviceId) {
List<ServiceInstance> instances = serviceCache.get(serviceId);
return instances != null ? instances.size() : 0;
}
}
@@ -0,0 +1,25 @@
package cn.novalon.manage.gateway.service;
import reactor.core.publisher.Mono;
/**
* 配置刷新服务接口
*
* 文件定义:定义网关配置动态刷新接口
* 涉及业务:配置热更新、配置版本管理
*
* @author 张翔
* @date 2026-04-14
*/
public interface IConfigRefreshService {
Mono<Void> refreshGatewayConfig();
Mono<Void> refreshRouteConfig();
Mono<Void> refreshFilterConfig();
Mono<String> getCurrentConfigVersion();
Mono<Boolean> isConfigChanged();
}
@@ -0,0 +1,44 @@
package cn.novalon.manage.gateway.service;
import org.springframework.cloud.gateway.route.RouteDefinition;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.util.List;
/**
* 动态路由服务接口
*
* 文件定义:定义网关路由的动态配置和管理接口
* 涉及业务:路由增删改查、路由刷新、路由缓存管理
*
* 核心功能:
* 1. 动态添加路由
* 2. 动态删除路由
* 3. 动态更新路由
* 4. 路由列表查询
* 5. 路由刷新
*
* @author 张翔
* @date 2026-04-14
*/
public interface IDynamicRouteService {
Mono<Boolean> addRoute(RouteDefinition routeDefinition);
Mono<Boolean> updateRoute(RouteDefinition routeDefinition);
Mono<Boolean> deleteRoute(String routeId);
Flux<RouteDefinition> getRoutes();
Mono<RouteDefinition> getRoute(String routeId);
Mono<Void> refreshRoutes();
Mono<Long> getRouteCount();
Mono<Boolean> routeExists(String routeId);
Mono<Void> clearRouteCache();
}
@@ -0,0 +1,27 @@
package cn.novalon.manage.gateway.service;
import reactor.core.publisher.Mono;
/**
* 请求缓存服务接口
*
* 文件定义:定义请求缓存管理接口
* 涉及业务:请求缓存、缓存清理、缓存统计
*
* @author 张翔
* @date 2026-04-14
*/
public interface IRequestCacheService {
Mono<Void> cacheRequest(String requestId, Object requestData);
Mono<Object> getCachedRequest(String requestId);
Mono<Boolean> removeCachedRequest(String requestId);
Mono<Void> clearExpiredCache();
Mono<Long> getCacheSize();
Mono<Boolean> isRequestCached(String requestId);
}
@@ -0,0 +1,41 @@
package cn.novalon.manage.gateway.service;
import org.springframework.cloud.client.ServiceInstance;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
/**
* 服务发现服务接口
*
* 文件定义:定义服务实例的发现、监控和管理接口
* 涉及业务:服务实例查询、健康检查、服务状态监控
*
* 核心功能:
* 1. 服务实例查询
* 2. 服务健康检查
* 3. 服务状态监控
* 4. 服务实例缓存
*
* @author 张翔
* @date 2026-04-14
*/
public interface IServiceDiscoveryService {
Flux<ServiceInstance> getInstances(String serviceId);
Flux<String> getServices();
Mono<Boolean> isServiceHealthy(String serviceId);
Mono<Long> getInstanceCount(String serviceId);
Mono<Void> refreshServiceCache(String serviceId);
Mono<Void> refreshAllServiceCache();
Mono<Long> getServiceCount();
Mono<Boolean> serviceExists(String serviceId);
Mono<Void> clearServiceCache();
}
@@ -1,5 +1,6 @@
package cn.novalon.manage.gateway.route;
package cn.novalon.manage.gateway.service.impl;
import cn.novalon.manage.gateway.service.IDynamicRouteService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.event.RefreshRoutesEvent;
@@ -11,12 +12,11 @@ import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* 动态路由服务
* 动态路由服务实现类
*
* 文件定义实现网关路由的动态配置和管理
* 涉及业务路由增删改查路由刷新路由缓存管理
@@ -29,10 +29,10 @@ import java.util.concurrent.ConcurrentHashMap;
* 5. 路由刷新
*
* @author 张翔
* @date 2026-03-26
* @date 2026-04-14
*/
@Service
public class DynamicRouteService {
public class DynamicRouteService implements IDynamicRouteService {
private static final Logger logger = LoggerFactory.getLogger(DynamicRouteService.class);
@@ -63,6 +63,7 @@ public class DynamicRouteService {
);
}
@Override
public Mono<Boolean> addRoute(RouteDefinition routeDefinition) {
if (routeDefinition == null || routeDefinition.getId() == null) {
logger.error("Invalid route definition: route or route ID is null");
@@ -85,6 +86,7 @@ public class DynamicRouteService {
});
}
@Override
public Mono<Boolean> updateRoute(RouteDefinition routeDefinition) {
if (routeDefinition == null || routeDefinition.getId() == null) {
logger.error("Invalid route definition: route or route ID is null");
@@ -100,18 +102,29 @@ public class DynamicRouteService {
logger.info("Updating route: {}", routeId);
return deleteRoute(routeId)
.flatMap(success -> {
if (success) {
return addRoute(routeDefinition);
}
return routeDefinitionWriter.delete(Mono.just(routeId))
.then(routeDefinitionWriter.save(Mono.just(routeDefinition)))
.then(Mono.fromRunnable(() -> {
routeCache.put(routeId, routeDefinition);
refreshRoutes();
logger.info("Route updated successfully: {}", routeId);
}))
.thenReturn(true)
.onErrorResume(error -> {
logger.error("Failed to update route: {}", routeId, error);
return Mono.just(false);
});
}
@Override
public Mono<Boolean> deleteRoute(String routeId) {
if (routeId == null || routeId.isEmpty()) {
logger.error("Invalid route ID: route ID is null or empty");
if (routeId == null) {
logger.error("Invalid route ID: null");
return Mono.just(false);
}
if (!routeCache.containsKey(routeId)) {
logger.warn("Route not found for deletion: {}", routeId);
return Mono.just(false);
}
@@ -130,71 +143,45 @@ public class DynamicRouteService {
});
}
public Flux<RouteDefinition> getAllRoutes() {
@Override
public Flux<RouteDefinition> getRoutes() {
return Flux.fromIterable(routeCache.values());
}
@Override
public Mono<RouteDefinition> getRoute(String routeId) {
if (routeId == null || routeId.isEmpty()) {
if (routeId == null) {
return Mono.empty();
}
RouteDefinition route = routeCache.get(routeId);
return route != null ? Mono.just(route) : Mono.empty();
return Mono.justOrEmpty(routeCache.get(routeId));
}
public void refreshRoutes() {
logger.info("Refreshing routes");
publisher.publishEvent(new RefreshRoutesEvent(this));
@Override
public Mono<Void> refreshRoutes() {
return Mono.fromRunnable(() -> {
publisher.publishEvent(new RefreshRoutesEvent(this));
logger.info("Routes refreshed");
});
}
public Mono<Boolean> batchAddRoutes(List<RouteDefinition> routeDefinitions) {
if (routeDefinitions == null || routeDefinitions.isEmpty()) {
logger.warn("No routes to add");
@Override
public Mono<Long> getRouteCount() {
return Mono.just((long) routeCache.size());
}
@Override
public Mono<Boolean> routeExists(String routeId) {
if (routeId == null) {
return Mono.just(false);
}
logger.info("Batch adding {} routes", routeDefinitions.size());
return Flux.fromIterable(routeDefinitions)
.flatMap(this::addRoute)
.all(success -> success)
.doOnSuccess(allSuccess -> {
if (allSuccess) {
logger.info("All routes added successfully");
} else {
logger.warn("Some routes failed to add");
}
});
return Mono.just(routeCache.containsKey(routeId));
}
public Mono<Boolean> batchDeleteRoutes(List<String> routeIds) {
if (routeIds == null || routeIds.isEmpty()) {
logger.warn("No routes to delete");
return Mono.just(false);
}
logger.info("Batch deleting {} routes", routeIds.size());
return Flux.fromIterable(routeIds)
.flatMap(this::deleteRoute)
.all(success -> success)
.doOnSuccess(allSuccess -> {
if (allSuccess) {
logger.info("All routes deleted successfully");
} else {
logger.warn("Some routes failed to delete");
}
});
@Override
public Mono<Void> clearRouteCache() {
return Mono.fromRunnable(() -> {
routeCache.clear();
logger.info("Route cache cleared");
});
}
public int getRouteCount() {
return routeCache.size();
}
public void clearRouteCache() {
logger.info("Clearing route cache");
routeCache.clear();
initializeRouteCache();
}
}
}
@@ -0,0 +1,182 @@
package cn.novalon.manage.gateway.service.impl;
import cn.novalon.manage.gateway.service.IServiceDiscoveryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.discovery.ReactiveDiscoveryClient;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* 服务发现服务实现类
*
* 文件定义:实现服务实例的发现、监控和管理
* 涉及业务:服务实例查询、健康检查、服务状态监控
*
* 核心功能:
* 1. 服务实例查询
* 2. 服务健康检查
* 3. 服务状态监控
* 4. 服务实例缓存
*
* @author 张翔
* @date 2026-04-14
*/
@Service
public class ServiceDiscoveryService implements IServiceDiscoveryService {
private static final Logger logger = LoggerFactory.getLogger(ServiceDiscoveryService.class);
private final ReactiveDiscoveryClient reactiveDiscoveryClient;
private final DiscoveryClient discoveryClient;
private final Map<String, List<ServiceInstance>> serviceCache = new ConcurrentHashMap<>();
private final Map<String, Long> lastUpdateTime = new ConcurrentHashMap<>();
private static final long CACHE_TTL_MS = 30000;
public ServiceDiscoveryService(
ReactiveDiscoveryClient reactiveDiscoveryClient,
DiscoveryClient discoveryClient) {
this.reactiveDiscoveryClient = reactiveDiscoveryClient;
this.discoveryClient = discoveryClient;
initializeServiceCache();
}
private void initializeServiceCache() {
logger.info("Initializing service cache");
discoveryClient.getServices().forEach(serviceId -> {
List<ServiceInstance> instances = discoveryClient.getInstances(serviceId);
if (!instances.isEmpty()) {
serviceCache.put(serviceId, instances);
lastUpdateTime.put(serviceId, System.currentTimeMillis());
logger.debug("Cached {} instances for service: {}", instances.size(), serviceId);
}
});
logger.info("Service cache initialized with {} services", serviceCache.size());
}
@Override
public Flux<ServiceInstance> getInstances(String serviceId) {
if (serviceId == null || serviceId.isEmpty()) {
logger.warn("Service ID is null or empty");
return Flux.empty();
}
if (isCacheValid(serviceId)) {
List<ServiceInstance> cachedInstances = serviceCache.get(serviceId);
if (cachedInstances != null && !cachedInstances.isEmpty()) {
logger.debug("Returning {} cached instances for service: {}",
cachedInstances.size(), serviceId);
return Flux.fromIterable(cachedInstances);
}
}
logger.debug("Fetching instances for service: {}", serviceId);
return reactiveDiscoveryClient.getInstances(serviceId)
.doOnNext(instance -> logger.debug("Found instance: {}:{} for service: {}",
instance.getHost(), instance.getPort(), serviceId))
.collectList()
.doOnNext(instances -> {
serviceCache.put(serviceId, instances);
lastUpdateTime.put(serviceId, System.currentTimeMillis());
logger.info("Updated cache with {} instances for service: {}",
instances.size(), serviceId);
})
.flatMapMany(Flux::fromIterable);
}
@Override
public Flux<String> getServices() {
return reactiveDiscoveryClient.getServices()
.doOnNext(serviceId -> logger.debug("Found service: {}", serviceId));
}
@Override
public Mono<Boolean> isServiceHealthy(String serviceId) {
return getInstances(serviceId)
.hasElements()
.map(hasInstances -> {
if (hasInstances) {
logger.debug("Service {} is healthy - has instances", serviceId);
return true;
} else {
logger.warn("Service {} is unhealthy - no instances found", serviceId);
return false;
}
});
}
@Override
public Mono<Long> getInstanceCount(String serviceId) {
return getInstances(serviceId)
.count()
.doOnNext(count -> logger.debug("Service {} has {} instances", serviceId, count));
}
@Override
public Mono<Void> refreshServiceCache(String serviceId) {
return Mono.fromRunnable(() -> {
if (serviceId != null) {
serviceCache.remove(serviceId);
lastUpdateTime.remove(serviceId);
logger.info("Refreshed cache for service: {}", serviceId);
}
});
}
@Override
public Mono<Void> refreshAllServiceCache() {
return Mono.fromRunnable(() -> {
serviceCache.clear();
lastUpdateTime.clear();
initializeServiceCache();
logger.info("Refreshed all service cache");
});
}
@Override
public Mono<Long> getServiceCount() {
return getServices()
.count()
.doOnNext(count -> logger.debug("Found {} services", count));
}
@Override
public Mono<Boolean> serviceExists(String serviceId) {
if (serviceId == null || serviceId.isEmpty()) {
return Mono.just(false);
}
return getServices()
.any(s -> s.equals(serviceId))
.doOnNext(exists -> logger.debug("Service {} exists: {}", serviceId, exists));
}
@Override
public Mono<Void> clearServiceCache() {
return Mono.fromRunnable(() -> {
serviceCache.clear();
lastUpdateTime.clear();
logger.info("Cleared service cache");
});
}
private boolean isCacheValid(String serviceId) {
Long lastUpdate = lastUpdateTime.get(serviceId);
if (lastUpdate == null) {
return false;
}
return System.currentTimeMillis() - lastUpdate < CACHE_TTL_MS;
}
}