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 configure spring cloud version 2.x Gateway dynamic routing

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

Share

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

This article focuses on "how to configure spring cloud 2.x version Gateway dynamic routing", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to configure spring cloud 2.x Gateway dynamic routing.

Summary of spring cloud version 2.x Gateway dynamic routing tutorial the Spring cloud used in this article is 2.1.8 RELEASM version calendar Greenwich.SR3 preface

After writing several articles about Spring Cloud Gateway, I found that the scope of knowledge involved in Gateway is too wide. I really have a deep understanding of "as deep as the sea as soon as I enter Spring cloud".

In the real production environment, Spring Cloud Gateway is used as the entrance to all traffic. In order to ensure the high availability of the system and avoid system restart as far as possible, dynamic routing of Spring Cloud Gateway is needed to deal with it. The routing configuration provided in the previous article "Gateway routing Gateway tutorial" will load the routing configuration and rules into memory when the system starts up. It is impossible to dynamically add, modify, or delete routing configurations and rules in memory without restarting the service.

Simple implementation of dynamic routing

The GatewayControllerEndpoint class is provided in the Spring Cloud Gateway source code to modify the routing configuration, but the official documentation does not seem to provide detailed instructions, but only a few simple api interfaces are briefly introduced. Interested partners can first check the official documentation (Chapter 11 Actuator API).

Lead to official documents:

The / gateway actuator endpoint allows to monitor and interact with a Spring Cloud Gateway application. To be remotely accessible, the endpoint has to be enabled and exposed via HTTP or JMX in the application properties.

1.1 add related pom dependencies

Add spring-boot-starter-actuator dependency to the original spring-gateway

Org.springframework.boot spring-boot-starter-actuator1.2 added configuration management: endpoints: web: exposure: include: "*" in application.yml

Configuration instructions: management.endpoints.web.exposure.include exposes all gateway endpoints

1.3 start the service

Start the service and visit http://localhost:8100/actuator/gateway/routes, this is where we can see all the routes information. Image-20191102225203034.png We can also access a single routing information: http://localhost:8100/actuator/gateway/routes/CompositeDiscoveryClient_EUREKA-CLIENT

Displayed as follows: image-20191102225853005.png

1.4 add or modify routing information

Gateway uses the GatewayControllerEndpoint class by default, and GatewayControllerEndpoint inherits the AbstractGatewayControllerEndpoint class.

The method provided: (only a few related methods are listed, and the guys of other methods can check the source code by themselves)

/ gateway/routes queries all routing information

/ gateway/routes/ {id} query individual information based on routing id

/ gateway/routes/ {id} @ PostMapping add a routing information

/ gateway/routes/ {id} @ DeleteMapping Delete a routing information

1.4.1 New rout

We can mimic a @ PostMapping request parameter based on the routing information returned by / gateway/routes

{"uri": "http://httpbin.org:80"," predicates ": [{" args ": {" pattern ":" / ribbon/** "}," name ":" Path "}]," filters ": []}

This is where we can send a post request through postman, as shown in the figure:

Response returns 1 to prove that it has been inserted successfully. We can view the routing information through http://localhost:8100/actuator/gateway/routes/, and the result is as follows:

The information in the red box of the screenshot is newly added

1.4.2 deleting routing information

We can simulate the DeleteMapping request directly with postman, http://localhost:8100/actuator/gateway/routes/addroutes

The display is as follows:

At this time, when we visit http://localhost:8100/actuator/gateway/routes, we can see that the newly added routes have been deleted successfully.

1.5 Summary

I have completed the dynamic routing based on the Spring Cloud Gateway default method, which I have mentioned in the preface, which is based on jvm memory implementation. Once the service is restarted, the new routing configuration information disappears completely. At this time, we can consider whether we can refer to GatewayControllerEndpoint, implement a set of dynamic routing methods ourselves, and then persist the routing information.

Custom dynamic routing 1.1 define related classes 1.1.1 define entity classes

Can customize the entity class, I stole a lazy here, directly used the Gateway RouteDefinition class, interested partners can refer to the RouteDefinition class their own expansion, and then write a Convert class to convert the custom class into RouteDefinition on it.

1.1.2 Custom RedisRouteDefinitionRepository class

I use redis as the persistence layer of routing configuration information here, so I write a RedisRouteDefinitionRepository.

Package spring.cloud.demo.spring.gateway.component;import com.google.common.collect.Lists;import org.springframework.cloud.gateway.route.RouteDefinition;import org.springframework.cloud.gateway.route.RouteDefinitionRepository;import org.springframework.cloud.gateway.support.NotFoundException;import org.springframework.stereotype.Component;import reactor.core.publisher.Flux;import reactor.core.publisher.Mono;import spring.cloud.demo.spring.gateway.redis.RedisUtils;import spring.cloud.demo.spring.gateway.util.JsonUtils;import javax.annotation.Resource Import java.util.List;/** * @ auther: maomao * @ DateT: 2019-11-03 * / @ Componentpublic class RedisRouteDefinitionRepository implements RouteDefinitionRepository {/ / stored key private final static String KEY = "gateway_dynamic_route"; @ Resource private RedisUtils redisUtils; / * get routing information * @ return * / @ Override public Flux getRouteDefinitions () {List gatewayRouteEntityList = Lists.newArrayList () RedisUtils.hgets (KEY) .stream () .forEach (route-> {RouteDefinition result = JsonUtils.parseJson (route.toString (), RouteDefinition.class); gatewayRouteEntityList.add (result);}); return Flux.fromIterable (gatewayRouteEntityList) } / * * New * @ param route * @ return * / @ Override public Mono save (Mono route) {return route.flatMap (routeDefinition-> {redisUtils.hset (KEY, routeDefinition.getId (), JsonUtils.toString (routeDefinition)); return Mono.empty ();}) } / * Delete * @ param routeId * @ return * / @ Override public Mono delete (Mono routeId) {return routeId.flatMap (id-> {if (redisUtils.hHashKey (KEY, id)) {redisUtils.hdel (KEY, id); return Mono.empty () } return Mono.defer (()-> Mono.error (new NotFoundException ("route definition is not found, routeId:" + routeId));});} 1.1.3 Custom Controller and Servicepackage spring.cloud.demo.spring.gateway.controller;import lombok.extern.slf4j.Slf4j;import org.springframework.cloud.gateway.route.RouteDefinition;import org.springframework.http.ResponseEntity;import org.springframework.web.bind.annotation.DeleteMapping Import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import reactor.core.publisher.Mono;import spring.cloud.demo.spring.gateway.service.GatewayDynamicRouteService;import javax.annotation.Resource / * * Custom dynamic routing * @ auther: maomao * @ DateT: 2019-11-03 * / @ RestController@RequestMapping ("/ gateway") @ Slf4jpublic class GatewayDynamicRouteController {@ Resource private GatewayDynamicRouteService gatewayDynamicRouteService; @ PostMapping ("/ add") public String create (@ RequestBody RouteDefinition entity) {int result = gatewayDynamicRouteService.add (entity); return String.valueOf (result) } @ PostMapping ("/ update") public String update (@ RequestBody RouteDefinition entity) {int result = gatewayDynamicRouteService.update (entity); return String.valueOf (result);} @ DeleteMapping ("/ delete/ {id}") public Mono delete (@ PathVariable String id) {return gatewayDynamicRouteService.delete (id);}} package spring.cloud.demo.spring.gateway.service;import org.springframework.cloud.gateway.event.RefreshRoutesEvent Import org.springframework.cloud.gateway.route.RouteDefinition;import org.springframework.cloud.gateway.support.NotFoundException;import org.springframework.context.ApplicationEventPublisher;import org.springframework.context.ApplicationEventPublisherAware;import org.springframework.http.ResponseEntity;import org.springframework.stereotype.Service;import reactor.core.publisher.Mono;import spring.cloud.demo.spring.gateway.component.RedisRouteDefinitionRepository;import javax.annotation.Resource;/** * @ auther: maomao * @ DateT: 2019-11-03 * / @ Servicepublic class GatewayDynamicRouteService implements ApplicationEventPublisherAware {@ Resource private RedisRouteDefinitionRepository redisRouteDefinitionRepository Private ApplicationEventPublisher applicationEventPublisher; / * add routing * @ param routeDefinition * @ return * / public int add (RouteDefinition routeDefinition) {redisRouteDefinitionRepository.save (Mono.just (routeDefinition)) .subscribe (); applicationEventPublisher.publishEvent (new RefreshRoutesEvent (this)); return 1 } / * Update * @ param routeDefinition * @ return * / public int update (RouteDefinition routeDefinition) {redisRouteDefinitionRepository.delete (Mono.just (routeDefinition.getId (); redisRouteDefinitionRepository.save (Mono.just (routeDefinition)) .subscribe (); applicationEventPublisher.publishEvent (new RefreshRoutesEvent (this)); return 1 } / * Delete * @ param id * @ return * / public Mono delete (String id) {return redisRouteDefinitionRepository.delete (Mono.just (id)) .then (Mono.defer (()-> Mono.just (ResponseEntity.ok (). Build () .onErrorResume (t-> t instanceof NotFoundException, t-> Mono.just (ResponseEntity.notFound (). Build () } @ Override public void setApplicationEventPublisher (ApplicationEventPublisher applicationEventPublisher) {this.applicationEventPublisher = applicationEventPublisher;}} 1.2 application.yml

For application.yml configuration to expose all endpoints of Gateway, you can check the previous configuration information.

1.3 start the service

To start the Spring cloud Gateway service, first visit http://localhost:8100/actuator/gateway/routes to view the existing routing configuration information. Then we request the add method, http://localhost:8100/gateway/add, with postman, as shown:

Notice the contents of the red box in the screenshot. It proves that it has been added successfully.

At this point, we are visiting http://localhost:8100/actuator/gateway/routes to see the results. If shown:

By the same token, we can access the update and delete methods, which I won't describe too much here.

Summary

The core principle of custom dynamic routing is to rewrite the gateway module, that is, the RedisRouteDefinitionRepository class mentioned earlier. I am lazy here without redefining the corresponding entity class. It should be noted here that the input parameters must follow the format configured in application.yml and then be converted to json. If the format is incorrect, an error will be reported.

Code address

GitHub address

"Srping Cloud 2.x Rookie tutorial" directory

Spring cloud version 2.x Eureka Server Service Registry tutorial

Spring cloud version 2.x Eureka Client Service provider tutorial

Spring cloud version 2.x Ribbon Service Discovery tutorial (includes integrated Hystrix circuit breaker mechanism)

Spring cloud version 2.x Feign Service Discovery tutorial (includes integrated Hystrix circuit breaker mechanism)

Spring cloud version 2.x Zuul routing Gateway tutorial

Spring cloud version 2.x config distributed configuration Center tutorial

Spring cloud version 2.x Hystrix Dashboard Circuit Breaker tutorial

Spring cloud version 2.x Gateway routing Gateway tutorial

Spring cloud version 2.x Gateway Custom filter tutorial

Spring cloud version 2.x Gateway fuse and current limiting tutorial

Spring cloud version 2.x Gateway dynamic routing tutorial

At this point, I believe you have a deeper understanding of "how to configure spring cloud 2.x Gateway dynamic routing". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

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