spring-cloud-gateway|-Spring Cloud Gateway 性能优化与调优 - return atomicLong

📅 2026-11-30 👤 拼多多助力营销技巧 📂 拼多多助力2027 👁️ 275 次阅读

handleError(Throwable error) {

// 错误处理逻辑

return Mono.fromCallable(() ->{

return createErrorResponse(error);

}).subscribeOn(Schedulers.boundedElastic());

}

private void validateRequestParameters(ServerRequest request) {

// 验证逻辑实现

}

private Object processBusinessLogic(ServerRequest request) {

// 业务逻辑实现

return new Object();

}

private Object addResponseMetadata(Object response) {

// 添加响应元数据

return response;

}

private Object createErrorResponse(Throwable error) {

// 创建错误响应

return new Object();

}

}

3. 连接池调优

3.1 HTTP客户端连接池优化

/**

* HTTP客户端连接池配置

* 优化后端服务连接池参数

*/

@Configuration

public class HttpClientPoolConfig {

@Bean

@Primary

public ConnectionProvider gatewayConnectionProvider() {

return ConnectionProvider.builder("gateway-connection-pool")

.maxConnections(1000) // 最大连接数

.pendingAcquireTimeout(Duration.ofSeconds(10)) // 获取连接超时时间

.pendingAcquireMaxCount(500) // 最大等待获取连接数

.maxIdleTime(Duration.ofSeconds(30)) // 最大空闲时间

.maxLifeTime(Duration.ofMinutes(10)) // 连接最大生命周期

.evictInBackground(Duration.ofSeconds(60)) // 后台清理间隔

.metrics(true) // 启用指标收集

.build();

}

@Bean

public HttpClient gatewayHttpClient(ConnectionProvider connectionProvider) {

return HttpClient.create(connectionProvider)

// 连接超时配置

.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000)

// 读写超时配置

.doOnConnected(conn ->

conn.addHandlerLast(new ReadTimeoutHandler(10))

.addHandlerLast(new WriteTimeoutHandler(10)))

// Keep-Alive配置

.keepAlive(true)

// 压缩配置

.compress(true)

// 代理配置(如果需要)

.proxy(spec ->spec.type(ProxyProvider.Proxy.HTTP)

.host("proxy.example.com")

.port(8080));

}

}

3.2 Redis连接池优化

# Redis连接池优化配置

spring:

redis:

host: ${REDIS_HOST:localhost}

port: ${REDIS_PORT:6379}

timeout: 2000ms

lettuce:

pool:

# 连接池配置

max-active: 500 # 最大连接数

max-idle: 200 # 最大空闲连接数

min-idle: 50 # 最小空闲连接数

max-wait: 1000ms # 最大等待时间

# 连接池行为配置

test-on-borrow: true

test-on-return: false

test-while-idle: true

time-between-eviction-runs: 30000ms # 空闲连接检查间隔

min-evictable-idle-time: 60000ms # 最小空闲时间

num-tests-per-eviction-run: 3 # 每次检查连接数

shutdown-timeout: 100ms

3.3 数据库连接池优化(如果需要)

# 数据库连接池优化配置(如果网关需要访问数据库)

spring:

datasource:

hikari:

maximum-pool-size: 20 # 最大连接池大小

minimum-idle: 5 # 最小空闲连接数

connection-timeout: 20000 # 连接超时时间

idle-timeout: 300000 # 空闲超时时间

max-lifetime: 1200000 # 连接最大生命周期

leak-detection-threshold: 60000 # 连接泄漏检测阈值

validation-timeout: 5000 # 连接验证超时时间

4. 缓存策略优化

4.1 多级缓存实现

/**

* 多级缓存服务

* 实现本地缓存+分布式缓存的多级缓存策略

*/

@Service

@Slf4j

public class MultiLevelCacheService {

private final LoadingCachelocalCache;

private final RedisTemplateredisTemplate;

public MultiLevelCacheService(RedisTemplateredisTemplate) {

this.redisTemplate = redisTemplate;

// 配置本地缓存

this.localCache = Caffeine.newBuilder()

.maximumSize(10000) // 最大缓存条目数

.expireAfterWrite(Duration.ofMinutes(10)) // 写入后10分钟过期

.expireAfterAccess(Duration.ofMinutes(5)) // 访问后5分钟过期

.recordStats() // 启用统计

.build(this::loadFromRedis); // 缓存未命中时从Redis加载

}

/**

* 获取缓存值(多级缓存)

*/

public Object get(String key) {

// 首先尝试本地缓存

Object value = localCache.getIfPresent(key);

if (value != null) {

log.debug("本地缓存命中: {}", key);

return value;

}

// 本地缓存未命中,尝试Redis缓存

value = redisTemplate.opsForValue().get(key);

if (value != null) {

log.debug("Redis缓存命中: {}", key);

// 将值放入本地缓存

localCache.put(key, value);

return value;

}

log.debug("缓存未命中: {}", key);

return null;

}

/**

* 设置缓存值

*/

public void put(String key, Object value, Duration expireTime) {

// 同时设置本地缓存和Redis缓存

localCache.put(key, value);

redisTemplate.opsForValue().set(key, value, expireTime);

log.debug("缓存已设置: {}", key);

}

/**

* 删除缓存

*/

public void remove(String key) {

// 同时删除本地缓存和Redis缓存

localCache.invalidate(key);

redisTemplate.delete(key);

log.debug("缓存已删除: {}", key);

}

/**

* 从Redis加载数据

*/

private Object loadFromRedis(String key) {

Object value = redisTemplate.opsForValue().get(key);

if (value != null) {

log.debug("从Redis加载数据: {}", key);

}

return value;

}

/**

* 获取缓存统计信息

*/

public CacheStats getCacheStats() {

com.github.benmanes.caffeine.cache.stats.CacheStats stats = localCache.stats();

return new CacheStats(

stats.hitCount(),

stats.missCount(),

stats.requestCount(),

stats.hitRate(),

localCache.estimatedSize()

);

}

/**

* 缓存统计信息类

*/

@Data

@AllArgsConstructor

public static class CacheStats {

private long hitCount;

private long missCount;

private long requestCount;

private double hitRate;

private long estimatedSize;

}

}

4.2 路由缓存优化

/**

* 路由缓存优化服务

* 优化路由匹配和缓存策略

*/

@Component

@Slf4j

public class OptimizedRouteCacheService {

// 路由缓存

private final LoadingCacherouteCache;

// 路由匹配结果缓存

private final LoadingCacherouteMatchCache;

public OptimizedRouteCacheService() {

// 路由定义缓存

this.routeCache = Caffeine.newBuilder()

.maximumSize(1000)

.expireAfterWrite(Duration.ofMinutes(5))

.recordStats()

.build(this::loadRouteFromSource);

// 路由匹配结果缓存(URL ->Route)

this.routeMatchCache = Caffeine.newBuilder()

.maximumSize(5000)

.expireAfterWrite(Duration.ofMinutes(1))

.recordStats()

.build(this::matchRouteFromDefinition);

}

/**

* 获取路由(带缓存)

*/

public Route getRoute(String routeId) {

return routeCache.get(routeId);

}

/**

* 匹配路由(带缓存)

*/

public Route matchRoute(String path) {

// 使用URL和谓词作为缓存键

String cacheKey = generateRouteMatchKey(path);

return routeMatchCache.get(cacheKey);

}

/**

* 生成路由匹配缓存键

*/

private String generateRouteMatchKey(String path) {

return "route_match:" + path;

}

/**

* 从源加载路由

*/

private Route loadRouteFromSource(String routeId) {

// 从路由定义源加载路由定义

// 这里需要根据实际的路由定义源实现

log.debug("从源加载路由: {}", routeId);

return null; // 简化实现

}

/**

* 从路由定义匹配路由

*/

private Route matchRouteFromDefinition(String cacheKey) {

// 从路由定义中匹配路由

// 这里需要实现具体的路由匹配逻辑

log.debug("匹配路由: {}", cacheKey);

return null; // 简化实现

}

/**

* 清空路由缓存

*/

public void clearRouteCache() {

routeCache.invalidateAll();

routeMatchCache.invalidateAll();

log.info("路由缓存已清空");

}

/**

* 刷新特定路由缓存

*/

public void refreshRouteCache(String routeId) {

routeCache.refresh(routeId);

log.debug("路由缓存已刷新: {}", routeId);

}

}

5. 路由性能优化

5.1 路由匹配优化

/**

* 优化的路由匹配器

* 提高路由匹配性能

*/

@Component

public class OptimizedRouteMatcher {

// 预编译的正则表达式缓存

private final MappatternCache = new ConcurrentHashMap<>();

// 路由索引,按路径长度排序以优化匹配顺序

private final AtomicReference> sortedRoutes = new AtomicReference<>();/**

* 匹配路由(优化版本)

*/

public Route matchRoute(ServerWebExchange exchange) {

String path = exchange.getRequest().getURI().getPath();

HttpMethod method = exchange.getRequest().getMethod();

Listroutes = sortedRoutes.get();

if (routes == null) {

// 首次访问时初始化路由索引

initializeRouteIndex();

routes = sortedRoutes.get();

}

// 按预排序的顺序匹配路由,优先匹配更具体的路径

for (Route route : routes) {

if (matchRoutePredicate(route, path, method)) {

return route;

}

}

return null;

}

/**

* 初始化路由索引

*/

private void initializeRouteIndex() {

// 这里需要从路由定义源获取所有路由

// 并按路径长度和匹配优先级排序

ListallRoutes = getAllRoutes(); // 需要实现获取所有路由的方法

// 按路径长度排序,更长的路径(更具体)优先

Listsorted = allRoutes.stream()

.sorted(Comparator.comparing(this::getRoutePathLength).reversed())

.collect(Collectors.toList());

sortedRoutes.set(sorted);

}

/**

* 获取路由路径长度

*/

private int getRoutePathLength(Route route) {

// 从路由谓词中提取路径信息并计算长度

// 简化实现,返回路径长度

return route.getPredicate().toString().length();

}

/**

* 匹配路由谓词

*/

private boolean matchRoutePredicate(Route route, String path, HttpMethod method) {

try {

// 使用预编译的正则表达式进行匹配

return route.getPredicate().test(exchange ->{

// 创建一个轻量级的exchange用于测试

return path.equals(exchange.getRequest().getURI().getPath()) &&

method.equals(exchange.getRequest().getMethod());

});

} catch (Exception e) {

// 匹配失败

return false;

}

}

/**

* 预编译正则表达式

*/

private Pattern compilePattern(String pattern) {

return patternCache.computeIfAbsent(pattern, Pattern::compile);

}

/**

* 获取所有路由(需要实现)

*/

private ListgetAllRoutes() {

// 实现获取所有路由的逻辑

return new ArrayList<>();

}

}

5.2 动态路由性能优化

/**

* 高性能动态路由服务

* 优化动态路由的加载和刷新性能

*/

@Service

@Slf4j

public class HighPerformanceDynamicRouteService {

private final RouteDefinitionWriter routeDefinitionWriter;

private final ApplicationEventPublisher publisher;

private final LoadingCacherouteDefinitionCache;

private final ReadWriteLock lock = new ReentrantReadWriteLock();

public HighPerformanceDynamicRouteService(RouteDefinitionWriter routeDefinitionWriter,

ApplicationEventPublisher publisher) {

this.routeDefinitionWriter = routeDefinitionWriter;

this.publisher = publisher;

// 配置路由定义缓存

this.routeDefinitionCache = Caffeine.newBuilder()

.maximumSize(1000)

.expireAfterWrite(Duration.ofMinutes(10))

.recordStats()

.build();

}

/**

* 批量添加路由定义

*/

public boolean batchAddRouteDefinitions(ListrouteDefinitions) {

lock.writeLock().lock();

try {

for (RouteDefinition routeDefinition : routeDefinitions) {

// 添加到缓存

routeDefinitionCache.put(routeDefinition.getId(), routeDefinition);

// 添加到网关

routeDefinitionWriter.save(Mono.just(routeDefinition)).block();

}

// 刷新路由

refreshRoutes();

log.info("批量添加路由定义完成,数量: {}", routeDefinitions.size());

return true;

} catch (Exception e) {

log.error("批量添加路由定义失败: {}", e.getMessage(), e);

return false;

} finally {

lock.writeLock().unlock();

}

}

/**

* 批量删除路由定义

*/

public boolean batchRemoveRouteDefinitions(ListrouteIds) {

lock.writeLock().lock();

try {

for (String routeId : routeIds) {

// 从缓存删除

routeDefinitionCache.invalidate(routeId);

// 从网关删除

routeDefinitionWriter.delete(Mono.just(routeId)).block();

}

// 刷新路由

refreshRoutes();

log.info("批量删除路由定义完成,数量: {}", routeIds.size());

return true;

} catch (Exception e) {

log.error("批量删除路由定义失败: {}", e.getMessage(), e);

return false;

} finally {

lock.writeLock().unlock();

}

}

/**

* 高效更新路由定义

*/

public boolean updateRouteDefinition(RouteDefinition routeDefinition) {

lock.writeLock().lock();

try {

String routeId = routeDefinition.getId();

// 先删除旧的

routeDefinitionWriter.delete(Mono.just(routeId)).block();

// 再添加新的

routeDefinitionWriter.save(Mono.just(routeDefinition)).block();

// 更新缓存

routeDefinitionCache.put(routeId, routeDefinition);

// 刷新路由

refreshRoutes();

log.info("路由定义更新完成: {}", routeId);

return true;

} catch (Exception e) {

log.error("更新路由定义失败: {}", e.getMessage(), e);

return false;

} finally {

lock.writeLock().unlock();

}

}

/**

* 刷新路由

*/

private void refreshRoutes() {

publisher.publishEvent(new RefreshRoutesEvent(this));

}

/**

* 获取路由定义

*/

public RouteDefinition getRouteDefinition(String routeId) {

lock.readLock().lock();

try {

return routeDefinitionCache.getIfPresent(routeId);

} finally {

lock.readLock().unlock();

}

}

}

6. 过滤器性能优化

6.1 高性能过滤器链

/**

* 高性能过滤器链优化

* 优化过滤器执行性能

*/

@Component

public class HighPerformanceFilterChain {

private final ListglobalFilters;

private final Map> routeFilters;

private final AtomicReference> sortedGlobalFilters;public HighPerformanceFilterChain(ListglobalFilters,

Map> routeFilters) {

this.globalFilters = globalFilters;

this.routeFilters = routeFilters;

this.sortedGlobalFilters = new AtomicReference<>();

// 预排序全局过滤器

initializeSortedGlobalFilters();

}

/**

* 初始化排序后的全局过滤器

*/

private void initializeSortedGlobalFilters() {

Listsorted = globalFilters.stream()

.sorted(Comparator.comparing(this::getFilterOrder))

.collect(Collectors.toList());

sortedGlobalFilters.set(sorted);

}

/**

* 获取过滤器顺序

*/

private int getFilterOrder(GatewayFilter filter) {

if (filter instanceof Ordered) {

return ((Ordered) filter).getOrder();

}

return 0; // 默认顺序

}

/**

* 执行优化的过滤器链

*/

public MonoexecuteFilterChain(ServerWebExchange exchange, Route route) {

// 获取当前路由的过滤器

ListcurrentRouteFilters = routeFilters.get(route.getId());

if (currentRouteFilters == null) {

currentRouteFilters = Collections.emptyList();

}

// 合并全局过滤器和路由过滤器,并排序

ListallFilters = new ArrayList<>();

allFilters.addAll(sortedGlobalFilters.get());

allFilters.addAll(currentRouteFilters);

// 按顺序排序

allFilters.sort(Comparator.comparing(this::getFilterOrder));

// 构建过滤器链

GatewayFilterChain chain = new DefaultGatewayFilterChain(allFilters);

return chain.filter(exchange);

}

/**

* 默认网关过滤器链实现

*/

private static class DefaultGatewayFilterChain implements GatewayFilterChain {

private final Listfilters;

private final AtomicInteger index = new AtomicInteger(0);

public DefaultGatewayFilterChain(Listfilters) {

this.filters = filters;

}

@Override

public Monofilter(ServerWebExchange exchange) {

if (index.get() >= filters.size()) {

// 所有过滤器执行完毕,继续处理

return Mono.empty();

}

GatewayFilter filter = filters.get(index.getAndIncrement());

return filter.filter(exchange, this);

}

}

}

6.2 条件过滤器优化

/**

* 条件过滤器优化

* 优化条件过滤器的执行性能

*/

@Component

@ConditionalOnProperty(name = "gateway.filter.optimization.enabled", havingValue = "true", matchIfMissing = true)

public class ConditionalFilterOptimization {

private final MapfilterConditionCache = new ConcurrentHashMap<>();

private final LoadingCacheconditionResultCache;

public ConditionalFilterOptimization() {

// 配置条件结果缓存

this.conditionResultCache = Caffeine.newBuilder()

.maximumSize(1000)

.expireAfterWrite(Duration.ofSeconds(30))

.build(this::evaluateCondition);

}

/**

* 评估过滤器条件(带缓存)

*/

public boolean shouldApplyFilter(String filterId, ServerWebExchange exchange) {

String cacheKey = generateConditionCacheKey(filterId, exchange);

return conditionResultCache.get(cacheKey);

}

/**

* 生成条件缓存键

*/

private String generateConditionCacheKey(String filterId, ServerWebExchange exchange) {

// 根据过滤器ID和请求特征生成缓存键

String path = exchange.getRequest().getURI().getPath();

String method = exchange.getRequest().getMethodValue();

String clientIp = getClientIp(exchange);

return String.format("%s:%s:%s:%s", filterId, path, method, clientIp);

}

/**

* 评估条件

*/

private Boolean evaluateCondition(String cacheKey) {

// 这里需要根据具体的条件评估逻辑实现

// 简化实现,返回true

return true;

}

/**

* 获取客户端IP

*/

private String getClientIp(ServerWebExchange exchange) {

String xForwardedFor = exchange.getRequest().getHeaders().getFirst("X-Forwarded-For");

if (xForwardedFor != null && !xForwardedFor.isEmpty()) {

return xForwardedFor.split(",")[0].trim();

}

String xRealIp = exchange.getRequest().getHeaders().getFirst("X-Real-IP");

if (xRealIp != null && !xRealIp.isEmpty()) {

return xRealIp;

}

InetSocketAddress remoteAddress = exchange.getRequest().getRemoteAddress();

return remoteAddress != null ? remoteAddress.getAddress().getHostAddress() : "unknown";

}

}

7. 内存与GC优化

7.1 JVM参数优化

# JVM优化参数示例

-Xms4g # 初始堆大小

-Xmx4g # 最大堆大小

-XX:NewRatio=1 # 新生代与老年代比例

-XX:SurvivorRatio=8 # Eden区与Survivor区比例

-XX:+UseG1GC # 使用G1垃圾收集器

-XX:MaxGCPauseMillis=200 # 最大GC暂停时间

-XX:G1HeapRegionSize=16m # G1区域大小

-XX:+ParallelRefProcEnabled # 并行处理引用

-XX:+UseStringDeduplication # 字符串去重

-XX:+OptimizeStringConcat # 优化字符串连接

7.2 对象池优化

/**

* 对象池服务

* 重用频繁创建的对象以减少GC压力

*/

@Component

public class ObjectPoolService {

// ServerWebExchange对象池

private final QueueexchangePool = new ConcurrentLinkedQueue<>();

private final int maxPoolSize = 100;

// 限流相关对象池

private final QueueatomicLongPool = new ConcurrentLinkedQueue<>();

/**

* 获取ServerWebExchange对象(从池中获取或创建新的)

*/

public ServerWebExchange getExchange() {

ServerWebExchange exchange = exchangePool.poll();

if (exchange == null) {

// 创建新的exchange对象(这里需要根据实际需求实现)

return null; // 简化实现

}

return exchange;

}

/**

* 回收ServerWebExchange对象

*/

public void returnExchange(ServerWebExchange exchange) {

if (exchangePool.size() < maxPoolSize) {

// 重置exchange对象状态

resetExchange(exchange);

exchangePool.offer(exchange);

}

}

/**

* 重置exchange对象状态

*/

private void resetExchange(ServerWebExchange exchange) {

// 重置exchange对象的可重用状态

// 这里需要根据实际的exchange实现来重置

}

/**

* 获取AtomicLong对象

*/

public AtomicLong getAtomicLong(long initialValue) {

AtomicLong atomicLong = atomicLongPool.poll();

if (atomicLong == null) {

return new AtomicLong(initialValue);

}

atomicLong.set(initialValue);

return atomicLong;

}

/**

* 回收AtomicLong对象

*/

public void returnAtomicLong(AtomicLong atomicLong) {

if (atomicLongPool.size() < maxPoolSize) {

atomicLong.set(0);

atomicLongPool.offer(atomicLong);

}

}

}

8. 监控与性能分析

8.1 性能监控指标

/**

* 网关性能监控服务

* 收集和分析网关性能指标

*/

@Service

@Slf4j

public class GatewayPerformanceMonitorService {

private final MeterRegistry meterRegistry;

// 性能指标

private final Timer requestProcessingTimer;

private final Counter requestCounter;

private final Gauge activeConnectionsGauge;

private final DistributionSummary responseSizeSummary;

public GatewayPerformanceMonitorService(MeterRegistry meterRegistry) {

this.meterRegistry = meterRegistry;

// 请求处理时间计时器

this.requestProcessingTimer = Timer.builder("gateway.request.processing.time")

.description("网关请求处理时间")

.register(meterRegistry);

// 请求计数器

this.requestCounter = Counter.builder("gateway.requests.total")

.description("网关总请求数")

.register(meterRegistry);

// 活跃连接数仪表

this.activeConnectionsGauge = Gauge.builder("gateway.active.connections")

.description("活跃连接数")

.register(meterRegistry, this, GatewayPerformanceMonitorService::getActiveConnections);

// 响应大小分布摘要

this.responseSizeSummary = DistributionSummary.builder("gateway.response.size")

.description("响应大小分布")

.baseUnit("bytes")

.register(meterRegistry);

}

/**

* 记录请求处理性能

*/

public void recordRequestPerformance(String path, String method, int status, long duration, long responseSize) {

// 记录请求处理时间

requestProcessingTimer.record(duration, TimeUnit.MILLISECONDS,

Tags.of("path", path, "method", method, "status", String.valueOf(status)));

// 记录请求计数

requestCounter.increment(Tags.of("path", path, "method", method, "status", String.valueOf(status)));

// 记录响应大小

if (responseSize > 0) {

responseSizeSummary.record(responseSize);

}

} 拼多多帮助力入口

/**

* 获取活跃连接数

*/

public double getActiveConnections() {

// 这里需要根据实际的连接管理实现获取活跃连接数

// 简化实现,返回示例值

return 50.0;

}

/**

* 获取性能统计信息

*/

public PerformanceStats getPerformanceStats() {

return new PerformanceStats(

getTimerMean(requestProcessingTimer),

getCounterCount(requestCounter),

getGaugeValue(activeConnectionsGauge),

getDistributionSummaryMean(responseSizeSummary)

);

}

/**

* 获取计时器平均值

*/

private double getTimerMean(Timer timer) {

return timer.totalTime(TimeUnit.MILLISECONDS) / Math.max(1, timer.count());

}

/**

* 获取计数器值

*/

private double getCounterCount(Counter counter) {

return counter.count();

}

/**

* 获取仪表值

*/

private double getGaugeValue(Gauge gauge) {

return gauge.value();

}

/**

* 获取分布摘要平均值

*/

private double getDistributionSummaryMean(DistributionSummary summary) {

return summary.totalAmount() / Math.max(1, summary.count());

}

/**

* 性能统计信息类

*/

@Data

@NoArgsConstructor

@AllArgsConstructor

public static class PerformanceStats {

private double avgProcessingTime; // 平均处理时间(毫秒)

private double totalRequests; // 总请求数

private double activeConnections; // 活跃连接数

private double avgResponseSize; // 平均响应大小

private long timestamp = System.currentTimeMillis();

}

}

8.2 性能分析过滤器

/**

* 性能分析过滤器

* 分析每个请求的性能指标

*/

@Component

@Order(-1000)

public class PerformanceAnalysisFilter implements GlobalFilter, Ordered {

private final GatewayPerformanceMonitorService performanceMonitorService;

public PerformanceAnalysisFilter(GatewayPerformanceMonitorService performanceMonitorService) {

this.performanceMonitorService = performanceMonitorService;

}

@Override

public Monofilter(ServerWebExchange exchange, GatewayFilterChain chain) {

long startTime = System.nanoTime();

return chain.filter(exchange).doFinally(signalType ->{

long duration = System.nanoTime() - startTime;

long durationMs = duration / 1_000_000; // 转换为毫秒

String path = exchange.getRequest().getURI().getPath();

String method = exchange.getRequest().getMethodValue();

int status = exchange.getResponse().getStatusCode() != null ?

exchange.getResponse().getStatusCode().value() : 0;

// 获取响应大小(近似值)

long responseSize = getApproximateResponseSize(exchange);

// 记录性能指标

performanceMonitorService.recordRequestPerformance(

path, method, status, durationMs, responseSize);

log.debug("请求性能 - path: {}, method: {}, status: {}, duration: {}ms, size: {}bytes",

path, method, status, durationMs, responseSize);

});

}

/**

* 获取近似的响应大小

*/

private long getApproximateResponseSize(ServerWebExchange exchange) {

// 这里需要根据实际的响应内容获取大小

// 简化实现,返回估算值

return 1024; // 1KB 估算

}

@Override

public int getOrder() {

return Ordered.LOWEST_PRECEDENCE;

}

}

9. 性能测试与基准

9.1 性能测试配置

# 性能测试配置

performance:

test:

enabled: true

threads: 100 # 测试线程数

ramp-up: 30 # 启动时间(秒)

duration: 300 # 测试持续时间(秒)

target-qps: 10000 # 目标QPS

warm-up-requests: 1000 # 预热请求数

report-interval: 10 # 报告间隔(秒)

optimization:

enabled: true

strategy: adaptive # 优化策略:adaptive, fixed, disabled

threshold:

response-time: 100 # 响应时间阈值(毫秒)

error-rate: 0.01 # 错误率阈值

9.2 性能基准测试服务

/**

* 性能基准测试服务

* 执行网关性能基准测试

*/

@Service

@Slf4j

public class PerformanceBenchmarkService {

private final WebClient webClient;

private final MeterRegistry meterRegistry;

private volatile boolean isBenchmarkRunning = false;

private final ExecutorService benchmarkExecutor = Executors.newFixedThreadPool(10);

public PerformanceBenchmarkService(WebClient.Builder webClientBuilder, MeterRegistry meterRegistry) {

this.webClient = webClientBuilder.build();

this.meterRegistry = meterRegistry;

}

/**

* 执行性能基准测试

*/

public PerformanceBenchmarkResult runBenchmark(PerformanceTestConfig config) {

if (isBenchmarkRunning) {

throw new IllegalStateException("性能测试已在运行中");

}

isBenchmarkRunning = true;

log.info("开始执行性能基准测试: {}", config);

try {

// 预热

warmUp(config);

// 执行基准测试

return executeBenchmark(config);

} finally {

isBenchmarkRunning = false;

log.info("性能基准测试完成");

}

}

/**

* 预热测试

*/

private void warmUp(PerformanceTestConfig config) {

log.info("开始预热测试,预热请求数: {}", config.getWarmUpRequests());

for (int i = 0; i < config.getWarmUpRequests(); i++) {

webClient.get()

.uri(config.getTestEndpoint())

.retrieve()

.bodyToMono(String.class)

.subscribeOn(Schedulers.boundedElastic())

.subscribe();

}

// 等待预热完成

try {

Thread.sleep(5000); // 等待5秒

} catch (InterruptedException e) {

Thread.currentThread().interrupt();

}

log.info("预热测试完成");

}

/**

* 执行基准测试

*/

private PerformanceBenchmarkResult executeBenchmark(PerformanceTestConfig config) {

long startTime = System.currentTimeMillis();

AtomicLong requestCount = new AtomicLong(0);

AtomicLong successCount = new AtomicLong(0);

AtomicLong errorCount = new AtomicLong(0);

AtomicLong totalResponseTime = new AtomicLong(0);

AtomicLong maxResponseTime = new AtomicLong(0);

AtomicLong minResponseTime = new AtomicLong(Long.MAX_VALUE);

CountDownLatch latch = new CountDownLatch(config.getThreads());

// 启动多个线程并发执行测试

for (int i = 0; i < config.getThreads(); i++) {

benchmarkExecutor.submit(() ->{

try {

long threadStartTime = System.currentTimeMillis();

while (System.currentTimeMillis() - threadStartTime < config.getDuration() * 1000) {

long requestStartTime = System.currentTimeMillis();

try {

// 执行请求

String response = webClient.get()

.uri(config.getTestEndpoint())

.retrieve()

.bodyToMono(String.class)

.timeout(Duration.ofSeconds(10))

.block();

long responseTime = System.currentTimeMillis() - requestStartTime;

// 更新统计信息

requestCount.incrementAndGet();

successCount.incrementAndGet();

totalResponseTime.addAndGet(responseTime);

maxResponseTime.accumulateAndGet(responseTime, Math::max);

minResponseTime.accumulateAndGet(responseTime, Math::min);

} catch (Exception e) {

requestCount.incrementAndGet();

errorCount.incrementAndGet();

log.warn("请求失败: {}", e.getMessage());

}

// 控制请求频率

if (config.getTargetQps() > 0) {

try {

Thread.sleep(1000 / config.getTargetQps());

} catch (InterruptedException e) {

Thread.currentThread().interrupt();

break;

}

}

}

} finally {

latch.countDown();

}

});

}

try {

latch.await(config.getDuration() + 30, TimeUnit.SECONDS);

} catch (InterruptedException e) {

Thread.currentThread().interrupt();

}

long endTime = System.currentTimeMillis();

long totalTime = endTime - startTime;

long totalRequests = requestCount.get();

long successfulRequests = successCount.get();

long failedRequests = errorCount.get();

double avgResponseTime = totalRequests > 0 ?

(double) totalResponseTime.get() / totalRequests : 0;

double qps = totalTime > 0 ? (double) totalRequests / (totalTime / 1000.0) : 0;

double errorRate = totalRequests > 0 ?

(double) failedRequests / totalRequests : 0;

PerformanceBenchmarkResult result = new PerformanceBenchmarkResult();

result.setTotalRequests(totalRequests);

result.setSuccessfulRequests(successfulRequests);

result.setFailedRequests(failedRequests);

result.setAvgResponseTime(avgResponseTime);

result.setMaxResponseTime(maxResponseTime.get());

result.setMinResponseTime(minResponseTime.get() == Long.MAX_VALUE ? 0 : minResponseTime.get());

result.setQps(qps);

result.setErrorRate(errorRate);

result.setTestDuration(totalTime);

result.setTimestamp(System.currentTimeMillis());

log.info("性能测试结果: QPS={}, 平均响应时间={}ms, 错误率={}",

result.getQps(), result.getAvgResponseTime(), result.getErrorRate());

return result;

}

/**

* 性能测试配置类

*/

@Data

@NoArgsConstructor

@AllArgsConstructor

public static class PerformanceTestConfig {

private String testEndpoint = "/test"; // 测试端点

private int threads = 100; // 并发线程数

private int duration = 300; // 测试持续时间(秒)

private int targetQps = 1000; // 目标QPS

private int warmUpRequests = 1000; // 预热请求数

}

/**

* 性能测试结果类

*/

@Data

@NoArgsConstructor

@AllArgsConstructor

public static class PerformanceBenchmarkResult {

private long totalRequests;

private long successfulRequests;

private long failedRequests;

private double avgResponseTime; // 平均响应时间(毫秒)

private long maxResponseTime; // 最大响应时间(毫秒)

private long minResponseTime; // 最小响应时间(毫秒)

private double qps; // 每秒请求数

private double errorRate; // 错误率

private long testDuration; // 测试持续时间(毫秒)

private long timestamp; // 测试时间戳

}

}

10. 性能优化最佳实践

10.1 优化检查清单

/**

* 性能优化检查清单服务

* 提供性能优化的检查和建议

*/

@Component

public class PerformanceOptimizationChecklist {

/**

* 性能优化检查项

*/

public enum OptimizationCheckItem {

CONNECTION_POOL_CONFIG("连接池配置", "检查连接池大小和超时配置"),

CACHE_STRATEGY("缓存策略", "实现多级缓存策略"),

ROUTE_OPTIMIZATION("路由优化", "优化路由匹配算法"),

FILTER_OPTIMIZATION("过滤器优化", "减少不必要的过滤器执行"),

JVM_TUNING("JVM调优", "优化JVM参数配置"),

GC_OPTIMIZATION("GC优化", "选择合适的垃圾收集器"),

ASYNC_PROCESSING("异步处理", "最大化异步处理比例"),

RESOURCE_REUSE("资源复用", "实现对象池等资源复用机制"),

METRICS_MONITORING("指标监控", "实施全面的性能监控");

private final String name;

private final String description;

OptimizationCheckItem(String name, String description) {

this.name = name;

this.description = description;

}

public String getName() { return name; }

public String getDescription() { return description; }

}

/**

* 执行性能优化检查

*/

public ListperformOptimizationCheck() {

Listresults = new ArrayList<>();

for (OptimizationCheckItem item : OptimizationCheckItem.values()) {

boolean isOptimized = checkOptimizationItem(item);

results.add(new OptimizationCheckResult(item, isOptimized));

}

return results;

}

/**

* 检查特定优化项

*/

private boolean checkOptimizationItem(OptimizationCheckItem item) {

switch (item) {

case CONNECTION_POOL_CONFIG:

return checkConnectionPoolConfig();

case CACHE_STRATEGY:

return checkCacheStrategy();

case ROUTE_OPTIMIZATION:

return checkRouteOptimization();

case FILTER_OPTIMIZATION:

return checkFilterOptimization();

case JVM_TUNING:

return checkJvmTuning();

case GC_OPTIMIZATION:

return checkGcOptimization();

case ASYNC_PROCESSING:

return checkAsyncProcessing();

case RESOURCE_REUSE:

return checkResourceReuse();

case METRICS_MONITORING:

return checkMetricsMonitoring();

default:

return false;

}

}

private boolean checkConnectionPoolConfig() {

// 检查连接池配置

return true; // 简化实现

}

private boolean checkCacheStrategy() {

// 检查缓存策略

return true; // 简化实现

}

private boolean checkRouteOptimization() {

// 检查路由优化

return true; // 简化实现

}

private boolean checkFilterOptimization() {

// 检查过滤器优化

return true; // 简化实现

}

private boolean checkJvmTuning() {

// 检查JVM调优

return true; // 简化实现

}

private boolean checkGcOptimization() {

// 检查GC优化

return true; // 简化实现

}

private boolean checkAsyncProcessing() {

// 检查异步处理

return true; // 简化实现

}

private boolean checkResourceReuse() {

// 检查资源复用

return true; // 简化实现

}

private boolean checkMetricsMonitoring() {

// 检查指标监控

return true; // 简化实现

}

/**

* 优化检查结果类

*/

@Data

@NoArgsConstructor

@AllArgsConstructor

public static class OptimizationCheckResult {

private OptimizationCheckItem item;

private boolean isOptimized;

private String recommendation;

}

}

11. 性能调优配置

11.1 完整性能优化配置

# application-performance.yml

server:

port: 8443

tomcat:

threads:

max: 200

min-spare: 10

spring:

main:

web-application-type: reactive

application:

name: gateway-web

cloud:

gateway:

httpclient:

pool:

max-connections: 1000

max-idle-time: 30s

max-life-time: 300s

pending-acquire-timeout: 10s

pending-acquire-max-count: 500

connect-timeout: 5000

response-timeout: 10s

pool-lazy: false

default-filters:

- name: RequestRateLimiter

args:

redis-rate-limiter.replenishRate: 100

redis-rate-limiter.burstCapacity: 200

key-resolver: "#{@apiKeyResolver}"

# Redis优化配置

redis:

host: ${REDIS_HOST:localhost}

port: ${REDIS_PORT:6379}

timeout: 2000ms

lettuce:

pool:

max-active: 500

max-idle: 200

min-idle: 50

max-wait: 1000ms

shutdown-timeout: 100ms

# 连接优化

webflux:

multipart:

max-in-memory-size: 2MB

max-disk-usage-per-part: 10MB

# 性能相关配置

performance:

optimization:

enabled: true

cache:

local:

max-size: 10000

expire-after-write: 600s

expire-after-access: 300s

distributed:

expire-time: 1800s

route:

cache-enabled: true

cache-expire-time: 300s

filter:

optimization-enabled: true

condition-cache-enabled: true

monitoring:

enabled: true

metrics:

collection-interval: 10s

retention-time: 86400s # 24小时

# 监控配置

management:

endpoints:

web:

exposure:

include: health,info,metrics,prometheus

metrics:

export:

prometheus:

enabled: true

step: 10s

distribution:

percentiles-histogram:

http:

server:

requests: true

percentiles:

http:

server:

requests: [0.5, 0.9, 0.95, 0.99]

# 日志配置(减少日志输出以提高性能)

logging:

level:

com.springboot.cloud.gateway: WARN

org.springframework.cloud.gateway: WARN

reactor.netty: WARN

pattern:

console: "%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n"

12. 最佳实践与建议

12.1 性能优化最佳实践

响应式优先:充分利用响应式编程优势资源复用:最大化连接和对象复用缓存策略:实施多级缓存策略异步处理:尽可能使用异步处理监控驱动:基于监控数据进行优化

12.2 性能调优建议

分阶段优化:逐步进行性能优化基准测试:建立性能基准持续监控:实施持续性能监控容量规划:合理规划系统容量

13. 总结

Spring Cloud Gateway的性能优化是一个系统工程,需要从多个维度进行考虑和实施。通过合理的配置优化、代码优化和架构优化,可以显著提升网关的性能表现。在实际应用中,需要根据具体的业务场景和性能要求,选择合适的优化策略并持续改进。

14. 参考资料

Spring WebFlux性能优化指南Reactor Netty性能调优文档微服务网关性能优化实践JVM性能调优指南

作者信息:本文详细介绍了Spring Cloud Gateway性能优化与调优,适合有一定微服务开发经验的开发者阅读。

注意事项:性能优化需要基于实际的性能测试数据,避免过度优化。

扩展阅读:如需深入了解响应式编程性能优化,请参考相关技术文档。

返回顶部暗黑模式

标签: 拼多多助力网站平台 赚钱项目 拼多多助力网 首码项目 手赚APP
拼多多助力营销技巧