Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Gateway to configure routing dynamics in Spring Cloud

2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

Many novices are not very clear about how to use Gateway to configure routing dynamics in Spring Cloud. In order to help you solve this problem, the following editor will explain it in detail. People with this need can come and learn. I hope you can get something.

8. Configure routing according to the configuration document

The configuration of Spring Cloud Gateway is controlled by a series of "RouteDefinitionLocator" interface implementation classes, which are as follows:

Public interface RouteDefinitionLocator {Flux getRouteDefinitions ();}

By default, through Spring Boot's @ ConfigurationProperties mechanism, Spring Cloud Gateway uses PropertiesRouteDefinitionLocator to load configuration information for routes from the configuration file. In the previous routing configuration, a quick configuration method was used, and specific parameter names can also be specified. For example, the effects of the following two configuration methods are exactly the same:

Spring: cloud: gateway: routes:-id: setstatus_route uri: http://example.org filters:-name: SetStatus args: status: 401-id: setstatusshortcut_route uri: http://example.org filters:-SetStatus=401

In some gateway application scenarios, attribute configuration is fine, but in some production environments, some routing configuration information may come from somewhere else, such as a database. In future Spring Cloud Gateway releases, some database-based RouteDefinitionLocator implementation classes, such as Redis,MongoDB, will also be added.

8.1 Fluent Java Routes API (add routing configuration using Java routing API code)

Some Fluent API defined in RouteLocatorBuilder can be used to configure relevant routing information in Java code, as shown in the following code:

/ / static imports from GatewayFilters and RoutePredicates@Bean public RouteLocator customRouteLocator (RouteLocatorBuilder builder, AddRequestHeaderGatewayFilterFactory throttle) {NameValueConfig requestHeader = new NameValueConfig (); requestHeader.setName ("routes-a"); requestHeader.setValue ("yes") Return builder.routes () .route (r-> r.host ("localhost:8080") .and () .path ("/ routes-api/a/**") .route (f-> {f.addResponseHeader ("X-TestHeader", "foobar")) Return f.redirect (HttpStatus.MOVED_PERMANENTLY.value (), "http://www.xinyues.com");" ) .uri ("http://localhost:8080").id("custom-1")) .route (r-> r.path (" / routes-api/b/** ") .route (f-> f.addResponseHeader (" X-AnotherHeader ") "baz") .uri ("http://localhost:8080").id("custom-2")) .route (r-> r.order (0) .host (" localhost:8080 "). And () .path (" / routes-api/c/** ") .route (f- > f.filter (throttle.apply (requestHeader)) .uri ("http://localhost:8080").id("custom-3")) .build () }

This code is implemented by referring to the original document, and the ThrottleGatewayFilterFactory above the original document can not be found. Here I have added a custom routes Id, which can be viewed from the source code: https://gitee.com/wgslucky/SpringCloud, start the source code project, enter: http://localhost:8080/actuator/gateway/routes in the browser, you can see all the routing information loaded by the gateway, and you can see the routing information in the code where the route id is custom-x Indicates that both the routing configuration added in Java and the routing configuration added in the configuration file are loaded into. It is more intuitive if the browser has the Json plug-in installed. This is a configured Json array of routes. According to the routing configuration in the above code, enter: http://localhost:8080/routes-api/a/test in the browser and you can see that you have successfully jumped to the target website, indicating that the routing configuration is successful. This form can also add some custom Predicate judgments, and the Predicates defined in RouteDefinitionLocator can use logical and. With Fluent Java Api, you can manipulate the Predicate class using and (), or (), and negate (). For example, the first route in the above code uses and () to add two Predicate.

8.2 DiscoveryClient Route Definition Locator uses the service discovery client to define routing information

Spring Cloud Gateway can use the service discovery client interface DiscoveryClient to obtain service registration information from the service attention center, and then configure the corresponding routes. Note that you need to add the following configuration to the configuration to enable this feature:

Spring.cloud.gateway.discovery.locator.enabled=true

Then make sure that the services of the implementation classes that have introduced DiscoveryClient discover client dependencies, such as Eureka,Consul or Zookeeper.

8.2.1 Configuring Predicates and Filters For DiscoveryClient Routes configures assertions and filters for routing information

By default, only one default Predicate and Filter are included in the routing information automatically configured by the service discovery client DiscoveryClient. The default Predicate is a Path Predicate, and the pattern is / serviceId/**,serviceId is the service ID obtained from the service discovery client. The default Filter is a rewrite path filter. Its regular expression is: / serviceId/ (?. *). Its function is to remove the serviceId from the request path and change it to / (. *). If you want to add custom Predicate and Filters, you can configure spring.cloud.gateway.discovery.locator.recipes [x] and spring.cloud.gateway.discovery.locator.filters [y] when using this configuration mode. The default Predicate and Filter are no longer retained. If you still need the original configuration, you need to manually add it to the configuration, as shown below: application.properties

Spring.cloud.gateway.discovery.locator.predicates [0] .name: Pathspring.cloud.gateway.discovery.locator.predicates [0] .args [pattern]: "'/'+ serviceId+'/**'" spring.cloud.gateway.discovery.locator.predicates [1] .name: Hostspring.cloud.gateway.discovery.locator.predicates [1] .args [pattern]: "'* * .foo.com'" spring.cloud.gateway.discovery.locator.filters [0] .name: Hystrixspring.cloud.gateway. Discovery.locator.filters [0] .args [name]: serviceIdspring.cloud.gateway.discovery.locator.filters [1] .name: RewritePathspring.cloud.gateway.discovery.locator.filters [1] .args [regexp]: "'/'+ serviceId +'/ (?. *)'" spring.cloud.gateway.discovery.locator.filters [1] .args [replacement]: "/ ${remaining}'"

Application.yml

Spring: cloud: gateway: discovery: locator: enabled: true predicates:-name: Path args: pattern: "'/'+ serviceId+'/test'" filters:-name: RedirectTo args: status: 301 url: "'http://www.xinyues.com'"

It is important to note that in these configurations, all configuration values are parsed by Spel, so if it is a string, you need to use quotation marks. For example, in application.yml, if it is configured like this: url: http://www.xinyues.com will report an error. For more information, please see: https://www.cnblogs.com/wgslucky/p/11743740.html

Application.yml this configuration is to retain the original default Predicate and Filter

Spring: cloud: gateway: discovery: locator: enabled: true predicates:-name: Path args: pattern: "'/'+ serviceId+'/**'" filters:-name: AddRequestHeader args: name: "'foo'" value: " 'bar' "- name: RewritePath args: regexp:" /' + serviceId +'/ (?. *)'"replacement:" / ${remaining}'"

You can see that all strings must be within single quotation marks.

Mobile phone support lazy person support desktop ipad tablet computer creative portable support multi-functional live broadcast Douyin photos landing bedside live car folding support

8.2.2 Source implementation

Download the source code: https://gitee.com/wgslucky/SpringCloud here

Modify application.yml to activate discoveryclient configuration file

Spring: profiles: active:-discoveryclient

Start the spring-cloud-gateway project

Start the spring-cloud-app-a project

Then enter: http://localhost:8080/actuator/gateway/routes in the browser, and you can see that the routing information that has been successfully defined to the spring-cloud-app-a service has been added, as shown below:

You can see that there is a default filter and predicate in it. And it can be seen that the routing information configured in the configuration file and the routing configuration information added in the java code are all loaded into the gateway, indicating that the three ways of configuring routing information can be used together.

Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report