服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - springcloud gateway如何实现路由和负载均衡

springcloud gateway如何实现路由和负载均衡

2021-09-25 20:34cuixinzhou Java教程

这篇文章主要介绍了springcloud gateway如何实现路由和负载均衡的操作,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

简介:

gateway主要是做路由 负载,过滤 主要是替代zuul 1.x 性能比zuul好 zuul是基于

Servlet ,gateway是基于spring-webflux 用的netty+reactor

yml文件

实现路由 负载 的配置 亲自测试

  1. spring:
  2. application:
  3. name: xgyx_gateway
  4. cloud:
  5. discovery:
  6. locator:
  7. enabled: true
  8. gateway:
  9. routes:
  10. - id: a #随便定义不重复就好
  11. uri: lb://xgyx-welfareservice-x #服务名称
  12. predicates:
  13. - Path=/m/** #前端访问需加入例如 http:ip:port/m
  14. filters:
  15. - StripPrefix=1 #访问后端服务过滤掉m 必填否则找不到后端服务也可以在服务加上统一路径
  16. - name: Hystrix #熔断
  17. args:
  18. name: default
  19. fallbackUri: forward:/defaultfallback #熔断后访问路径
  20. - id: b
  21. uri: lb://xgyx-welfareservice
  22. predicates:
  23. - Path=/welfare/**
  24. filters:
  25. - StripPrefix=1
  26. - name: Hystrix
  27. args:
  28. name: default
  29. fallbackUri: forward:/fallback
  30. #熔断时间
  31. hystrix:
  32. command:
  33. default:
  34. execution:
  35. isolation:
  36. strategy: SEMAPHORE
  37. thread:
  38. timeoutInMilliseconds: 300000 #熔断时间

上面是用了两天时间根据官网上的demo和说明自己测的可以使用 上面 stripPrefix 用的是 PrefixPath 过滤器 其他过滤器使用可以看官网

springcloud gateway 自定义负载均衡

相关类及接口

LoadbalancerClientFilter:使用ribbon负载均衡,默认使用该类(已不推荐使用)

  1. /** @deprecated */
  2. @Deprecated
  3. public class LoadBalancerClientFilter implements GlobalFilter, Ordered {
  4. public static final int LOAD_BALANCER_CLIENT_FILTER_ORDER = 10100;
  5. private static final Log log = LogFactory.getLog(LoadBalancerClientFilter.class);
  6. protected final LoadBalancerClient loadBalancer;
  7. private LoadBalancerProperties properties;
  8.  
  9. public LoadBalancerClientFilter(LoadBalancerClient loadBalancer, LoadBalancerProperties properties) {
  10. this.loadBalancer = loadBalancer;
  11. this.properties = properties;
  12. }
  13.  
  14. public int getOrder() {
  15. return 10100;
  16. }
  17.  
  18. public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
  19. URI url = (URI)exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR);
  20. String schemePrefix = (String)exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_SCHEME_PREFIX_ATTR);
  21. if (url != null && ("lb".equals(url.getScheme()) || "lb".equals(schemePrefix))) {
  22. ServerWebExchangeUtils.addOriginalRequestUrl(exchange, url);
  23. if (log.isTraceEnabled()) {
  24. log.trace("LoadBalancerClientFilter url before: " + url);
  25. }
  26.  
  27. ServiceInstance instance = this.choose(exchange);
  28. if (instance == null) {
  29. throw NotFoundException.create(this.properties.isUse404(), "Unable to find instance for " + url.getHost());
  30. } else {
  31. URI uri = exchange.getRequest().getURI();
  32. String overrideScheme = instance.isSecure() ? "https" : "http";
  33. if (schemePrefix != null) {
  34. overrideScheme = url.getScheme();
  35. }
  36.  
  37. URI requestUrl = this.loadBalancer.reconstructURI(new DelegatingServiceInstance(instance, overrideScheme), uri);
  38. if (log.isTraceEnabled()) {
  39. log.trace("LoadBalancerClientFilter url chosen: " + requestUrl);
  40. }
  41.  
  42. exchange.getAttributes().put(ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR, requestUrl);
  43. return chain.filter(exchange);
  44. }
  45. } else {
  46. return chain.filter(exchange);
  47. }
  48. }
  49.  
  50. protected ServiceInstance choose(ServerWebExchange exchange) {
  51. return this.loadBalancer.choose(((URI)exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR)).getHost());
  52. }
  53. }

说明:默认使用该类,可通过下述方法使用ReactiveLoadbalancerClientFilter

​"You already have RibbonLoadBalancerClient on your classpath. It will be used by default.
As Spring Cloud Ribbon is in maintenance mode. We recommend switching to " + BlockingLoadBalancerClient.class.getSimpleName() + " instead.
In order to use it, set the value of `spring.cloud.loadbalancer.ribbon.enabled` to `false`
or remove spring-cloud-starter-netflix-ribbon from your project."

ReactiveLoadBalancerClientFilter:负载均衡拦截器

  1. public class ReactiveLoadBalancerClientFilter implements GlobalFilter, Ordered {
  2. private static final Log log = LogFactory.getLog(ReactiveLoadBalancerClientFilter.class);
  3. private static final int LOAD_BALANCER_CLIENT_FILTER_ORDER = 10150;
  4. private final LoadBalancerClientFactory clientFactory;
  5. private LoadBalancerProperties properties;
  6. public ReactiveLoadBalancerClientFilter(LoadBalancerClientFactory clientFactory, LoadBalancerProperties properties) {
  7. this.clientFactory = clientFactory;
  8. this.properties = properties;
  9. }
  10.  
  11. public int getOrder() {
  12. return 10150;
  13. }
  14.  
  15. public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
  16. URI url = (URI)exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR);
  17. String schemePrefix = (String)exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_SCHEME_PREFIX_ATTR);
  18. if (url != null && ("lb".equals(url.getScheme()) || "lb".equals(schemePrefix))) {
  19. //url不为null且协议为lb,或者url以lb开头
  20.  
  21. ServerWebExchangeUtils.addOriginalRequestUrl(exchange, url);
  22. if (log.isTraceEnabled()) {
  23. log.trace(ReactiveLoadBalancerClientFilter.class.getSimpleName() + " url before: " + url);
  24. }
  25.  
  26. return this.choose(exchange).doOnNext((response) -> {
  27. //获取ServiceInstance实例,进行一些处理
  28.  
  29. if (!response.hasServer()) {
  30. //如果没有serviceInstance,直接抛出异常
  31.  
  32. throw NotFoundException.create(this.properties.isUse404(), "Unable to find instance for " + url.getHost());
  33. } else { //如果有serviceInstance,进行相关处理
  34. URI uri = exchange.getRequest().getURI();
  35. String overrideScheme = null;
  36. if (schemePrefix != null) {
  37. overrideScheme = url.getScheme();
  38. }
  39.  
  40. DelegatingServiceInstance serviceInstance = new DelegatingServiceInstance((ServiceInstance)response.getServer(), overrideScheme);
  41. URI requestUrl = LoadBalancerUriTools.reconstructURI(serviceInstance, uri);
  42. if (log.isTraceEnabled()) {
  43. log.trace("LoadBalancerClientFilter url chosen: " + requestUrl);
  44. }
  45.  
  46. exchange.getAttributes().put(ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR, requestUrl);
  47. }
  48. }).then(chain.filter(exchange));
  49. } else {
  50. return chain.filter(exchange); //如果获取不到serviceInstance,直接进行后续过滤
  51. }
  52. }
  53.  
  54. private Mono<Response<ServiceInstance>> choose(ServerWebExchange exchange) {
  55. URI uri = (URI)exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR);
  56. ReactorLoadBalancer<ServiceInstance> loadBalancer = (ReactorLoadBalancer)this.clientFactory.getInstance(uri.getHost(), ReactorLoadBalancer.class, new Class[]{ServiceInstance.class});
  57. if (loadBalancer == null) {
  58. throw new NotFoundException("No loadbalancer available for " + uri.getHost());
  59. } else {
  60. return loadBalancer.choose(this.createRequest());
  61. }
  62. }//选择服务实例
  63.  
  64. private Request createRequest() {
  65. return ReactiveLoadBalancer.REQUEST;
  66. }
  67. }

ReactorLoadBalancer:负载均衡接口

  1. public interface ReactorLoadBalancer<T> extends ReactiveLoadBalancer<T> {
  2. Mono<Response<T>> choose(Request request);
  3. default Mono<Response<T>> choose() {
  4. return this.choose(REQUEST);
  5. }
  6. }
  7. ***********************
  8. public interface ReactorServiceInstanceLoadBalancer extends ReactorLoadBalancer<ServiceInstance> {
  9. }

RoundRobinLoadbalancer:负载均衡使用轮询

  1. public class RoundRobinLoadBalancer implements ReactorServiceInstanceLoadBalancer {
  2. private static final Log log = LogFactory.getLog(RoundRobinLoadBalancer.class);
  3. private final AtomicInteger position;
  4. private ObjectProvider<ServiceInstanceListSupplier> serviceInstanceListSupplierProvider;
  5. private final String serviceId;
  6.  
  7. ************
  8. 构造方法
  9.  
  10. public RoundRobinLoadBalancer(ObjectProvider<ServiceInstanceListSupplier> serviceInstanceListSupplierProvider, String serviceId) {
  11. public RoundRobinLoadBalancer(ObjectProvider<ServiceInstanceListSupplier> serviceInstanceListSupplierProvider, String serviceId, int seedPosition) {
  12.  
  13. ************
  14. 普通方法
  15.  
  16. public Mono<Response<ServiceInstance>> choose(Request request) {
  17. if (this.serviceInstanceListSupplierProvider != null) {
  18. ServiceInstanceListSupplier supplier = (ServiceInstanceListSupplier)this.serviceInstanceListSupplierProvider.getIfAvailable(NoopServiceInstanceListSupplier::new);
  19. return ((Flux)supplier.get()).next().map(this::getInstanceResponse);
  20. } else {
  21. ServiceInstanceSupplier supplier = (ServiceInstanceSupplier)this.serviceInstanceSupplier.getIfAvailable(NoopServiceInstanceSupplier::new);
  22. return ((Flux)supplier.get()).collectList().map(this::getInstanceResponse);
  23. }
  24. }
  25.  
  26. private Response<ServiceInstance> getInstanceResponse(List<ServiceInstance> instances) {
  27. if (instances.isEmpty()) {
  28. log.warn("No servers available for service: " + this.serviceId);
  29. return new EmptyResponse();
  30. } else {
  31. int pos = Math.abs(this.position.incrementAndGet());
  32. ServiceInstance instance = (ServiceInstance)instances.get(pos % instances.size());
  33. return new DefaultResponse(instance);
  34. }
  35. }//使用轮询获取实例
  36. }

示例:

参数id为偶数时,输出hello new version

网关

配置文件

  1. spring:
  2. application:
  3. name: hello-gateway
  4. cloud:
  5. consul:
  6. host: 172.18.0.20
  7. port: 8500
  8. loadbalancer:
  9. ribbon:
  10. enabled: false
  11. gateway:
  12. routes:
  13. - id: myRoute
  14. uri: lb://hello-service
  15. predicates:
  16. - Path=/hello

自定义过滤器

  1. @Component
  2. public class CustomLoadBalancerClientFilter implements GlobalFilter, Ordered {
  3. private static final Log log = LogFactory.getLog(org.springframework.cloud.gateway.filter.ReactiveLoadBalancerClientFilter.class);
  4.  
  5. @Resource
  6. private final LoadBalancerClientFactory clientFactory;
  7.  
  8. @Resource
  9. private LoadBalancerProperties properties;
  10.  
  11. public CustomLoadBalancerClientFilter(LoadBalancerClientFactory clientFactory, LoadBalancerProperties properties) {
  12. this.clientFactory = clientFactory;
  13. this.properties = properties;
  14. }
  15.  
  16. public int getOrder() {
  17. return 10149;
  18. }
  19.  
  20. public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
  21. URI url = exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR);
  22. String schemePrefix = exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_SCHEME_PREFIX_ATTR);
  23. if (url != null && ("lb".equals(url.getScheme()) || "lb".equals(schemePrefix))) {
  24. ServerWebExchangeUtils.addOriginalRequestUrl(exchange, url);
  25. if (log.isTraceEnabled()) {
  26. log.trace(ReactiveLoadBalancerClientFilter.class.getSimpleName() + " url before: " + url);
  27. }
  28.  
  29. return this.choose(exchange).doOnNext((response) -> {
  30. if (!response.hasServer()) {
  31. throw NotFoundException.create(this.properties.isUse404(), "Unable to find instance for " + url.getHost());
  32. } else {
  33. URI uri = exchange.getRequest().getURI();
  34. String overrideScheme = null;
  35. if (schemePrefix != null) {
  36. overrideScheme = url.getScheme();
  37. }
  38.  
  39. int id=Integer.parseInt(Objects.requireNonNull(exchange.getRequest().getQueryParams().getFirst("id")));
  40. if (id%2==0){
  41. while (!"new".equals(response.getServer().getMetadata().get("version"))){
  42. try {
  43. response=this.choose(exchange).toFuture().get();
  44. }catch (Exception e){
  45. System.out.println(e.getMessage());
  46. }
  47. }
  48. }
  49.  
  50. DelegatingServiceInstance serviceInstance = new DelegatingServiceInstance(response.getServer(), overrideScheme);
  51.  
  52. System.out.println(exchange.getRequest().getQueryParams().getFirst("id")+"对应server的version为:"+serviceInstance.getMetadata().get("version"));
  53. URI requestUrl = LoadBalancerUriTools.reconstructURI(serviceInstance, uri);
  54. if (log.isTraceEnabled()) {
  55. log.trace("LoadBalancerClientFilter url chosen: " + requestUrl);
  56. }
  57.  
  58. exchange.getAttributes().put(ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR, requestUrl);
  59. }
  60. }).then(chain.filter(exchange));
  61. } else {
  62. return chain.filter(exchange);
  63. }
  64. }
  65.  
  66. private Mono<Response<ServiceInstance>> choose(ServerWebExchange exchange) {
  67. URI uri = exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR);
  68. assert uri != null;
  69. ReactorLoadBalancer<ServiceInstance> loadBalancer = this.clientFactory.getInstance(uri.getHost(), ReactorLoadBalancer.class, new Class[]{ServiceInstance.class});
  70. if (loadBalancer == null) {
  71. throw new NotFoundException("No loadbalancer available for " + uri.getHost());
  72. } else {
  73. return loadBalancer.choose(this.createRequest());
  74. }
  75. }
  76.  
  77. private Request createRequest() {
  78. return ReactiveLoadBalancer.REQUEST;
  79. }
  80. }

同名应用hello-service1

配置文件

  1. spring:
  2. application:
  3. name: hello-service
  4. cloud:
  5. consul:
  6. host: 172.18.0.20
  7. port: 8500
  8. discovery:
  9. instance-id: ${spring.application.name}-${random.int}
  10. tags: version=old

controller 层

  1. @RestController
  2. public class HelloController {
  3. @RequestMapping("/hello")
  4. public String hello(){
  5. return "hello old version";
  6. }
  7. }

同名应用hello-service2

配置文件

  1. spring:
  2. application:
  3. name: hello-service
  4. cloud:
  5. consul:
  6. host: 172.18.0.20
  7. port: 8500
  8. discovery:
  9. instance-id: ${spring.application.name}-${random.int}
  10. tags: version=new

controller 层

  1. @RestController
  2. public class HelloController {
  3. @RequestMapping("/hello")
  4. public String hello(){
  5. return "hello new version";
  6. }
  7. }

测试输出

consul注册的应用

springcloud gateway如何实现路由和负载均衡

参数测试

springcloud gateway如何实现路由和负载均衡

当id为偶数时,输出为hello new version

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。

原文链接:https://blog.csdn.net/cuixinzhou/article/details/93379130

延伸 · 阅读

精彩推荐