Spring Cloud Gateway 与 Nacos 的完美结合
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.filter.factory.RequestRateLimiterGatewayFilterFactory;
import org.springframework.cloud.gateway.handler.FilteringWebHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.alibaba.csp.sentinel.adapter.gateway.sc.SentinelGatewayFilter;
import com.alibaba.csp.sentinel.adapter.gateway.sc.exception.SentinelGatewayBlockExceptionHandler;
@Configuration
public class GatewayConfiguration {
@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
return builder.routes()
.route("path_route", r -> r.path("/api/**")
.uri("http://your-service")
.filters(f -> f
.filter(new SentinelGatewayFilter())
.requestRateLimiter(config -> config
.setKeyResolver(new MyKeyResolver())
.setRateLimiter(new MyRateLimiter()))))
.build();
}
@Bean
public SentinelGatewayBlockExceptionHandler sentinelGatewayBlockExceptionHandler() {
return new SentinelGatewayBlockExceptionHandler();
}
}
这个代码示例展示了如何在Spring Cloud Gateway中使用Nacos作为流量控制和熔断的实现。它定义了一个自定义的路由定位器,并为所有通过/api/**
路径的请求配置了Sentinel的网关过滤器,同时也配置了自定义的限流和熔断逻辑。
评论已关闭