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

Dynamic routing of Spring Cloud Zuul and example Analysis of Integrated Nacos implementation

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

Share

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

The dynamic routing of Spring Cloud Zuul and the example analysis of integrated Nacos implementation. Aiming at this problem, this article introduces the corresponding analysis and solution in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible method.

I. explanation

The core concept of the gateway is routing configuration and routing rules, and as the entrance to all request traffic, in order to ensure high reliability and high availability in the actual production environment, it is necessary to avoid restart, so it is very necessary to implement dynamic routing. The following mainly introduces the idea of implementation, and uses Nacos as the data source to explain.

II. Key points of implementation

To achieve dynamic routing, you only need to pay attention to the following four points

When the gateway starts, how to load the dynamically routed data

Static routing and dynamic routing shall prevail. Ps: static routing refers to the dead route configuration written in the configuration file.

Listen for changes in data sources for dynamic routing

How to notify zuul to refresh the route when the data changes

Third, the concrete realization is 3.1. Data loading for dynamic routing

Override the locateRoutes method of the SimpleRouteLocator class, which loads the routing configuration, and the parent class obtains the routing configuration in properties. This method can be extended to obtain the configuration dynamically.

Here, static route and dynamic route coexist, and the same route id is overridden by dynamic route first.

AbstractDynRouteLocator Abstract Class

Public abstract class AbstractDynRouteLocator extends SimpleRouteLocator implements RefreshableRouteLocator {private ZuulProperties properties; public AbstractDynRouteLocator (String servletPath, ZuulProperties properties) {super (servletPath, properties); this.properties = properties;} @ Override public void refresh () {doRefresh ();} @ Override protected Map locateRoutes () {LinkedHashMap routesMap = new LinkedHashMap () / / load static routing information routesMap.putAll (super.locateRoutes ()) from application.properties; / / load dynamic routing information routesMap.putAll (loadDynamicRoute ()) from data source; / / optimize the configuration LinkedHashMap values = new LinkedHashMap (); for (Map.Entry entry: routesMap.entrySet ()) {String path = entry.getKey () / / Prepend with slash if not already present. If (! path.startsWith ("/")) {path = "/" + path;} if (StringUtils.hasText (this.properties.getPrefix () {path = this.properties.getPrefix () + path; if (! path.startsWith ("/")) {path = "/" + path }} values.put (path, entry.getValue ());} return values;} / * * load routing configuration, and subclasses implement * / public abstract Map loadDynamicRoute ();}

Since there are many ways to dynamically route data, such as Nacos, Redis, Zookeeper, DB, etc., an abstract class is defined here, and the loadDynamicRoute method is defined by the concrete implementation class.

3.2. Nacos routing implementation class

NacosDynRouteLocator class

3.2.1. Implement the loadDynamicRoute method to get dynamic data @ Overridepublic Map loadDynamicRoute () {Map routes = new LinkedHashMap (); if (zuulRouteEntities = = null) {zuulRouteEntities = getNacosConfig ();} for (ZuulRouteEntity result: zuulRouteEntities) {if (StrUtil.isBlank (result.getPath ()) | |! result.isEnabled ()) {continue;} ZuulRoute zuulRoute = new ZuulRoute (); BeanUtil.copyProperties (result, zuulRoute) Routes.put (zuulRoute.getPath (), zuulRoute);} return routes;} private List getNacosConfig () {try {String content = nacosConfigProperties.configServiceInstance (). GetConfig (ZUUL_DATA_ID, ZUUL_GROUP_ID,5000); return getListByStr (content);} catch (NacosException e) {log.error ("listenerNacos-error", e);} return new ArrayList (0);} 3.2.2. Add NacosListener snooping routing data change private void addListener () {try {nacosConfigProperties.configServiceInstance () .addListener (ZUUL_DATA_ID, ZUUL_GROUP_ID, new Listener () {@ Override public Executor getExecutor () {return null) } @ Override public void receiveConfigInfo (String configInfo) {/ / assign routing information locator.setZuulRouteEntities (getListByStr (configInfo)); RoutesRefreshedEvent routesRefreshedEvent = new RoutesRefreshedEvent (locator); publisher.publishEvent (routesRefreshedEvent);}}) } catch (NacosException e) {log.error ("nacos-addListener-error", e);}}

Note that after the routing data changes, you don't need to refresh the route manually, you just need to send a RoutesRefreshedEvent event to zuul. Zuul has a ZuulRefreshListener class that listens to the event to help us refresh the route.

The complete code implementation of this class can be seen as follows:

Https://gitee.com/zlt2000/microservices-platform/blob/master/zlt-gateway/zuul-gateway/src/main/java/com/central/gateway/route/nacos/NacosDynRouteLocator.java

3.3. The configuration class creates the Bean of NacosDynRouteLocator

DynamicZuulRouteConfig class

@ Configuration@ConditionalOnProperty (prefix = "zlt.gateway.dynamicRoute", name = "enabled", havingValue = "true") public class DynamicZuulRouteConfig {@ Autowired private ZuulProperties zuulProperties; @ Autowired private DispatcherServletPath dispatcherServletPath; / * Nacos implementation * / @ Configuration@ConditionalOnProperty (prefix = "zlt.gateway.dynamicRoute", name = "dataType", havingValue = "nacos", matchIfMissing = true) public class NacosZuulRoute {@ Autowired private NacosConfigProperties nacosConfigProperties @ Autowired private ApplicationEventPublisher publisher; @ Bean public NacosDynRouteLocator nacosDynRouteLocator () {return new NacosDynRouteLocator (nacosConfigProperties, publisher, dispatcherServletPath.getPrefix (), zuulProperties);}

Here, custom configuration is used to control whether the dynamic routing function is enabled.

3.4. Add Nacos routing configuration

New configuration item:

Data Id:zuul-routes

Group:ZUUL_GATEWAY

Configuration content:

[{"enabled": true, "id": "csdn", "path": "/ csdn/**", "retryable": false, "stripPrefix": true, "url": "https://www.csdn.net/"}, {" enabled ": true," id ":" github "," path ":" / github/** "," retryable ": false "stripPrefix": true, "url": "http://github.com/"}]

Add two routing data

IV. Testing

Start the gateway to view all the routing information of the gateway through the / actuator/routes endpoint

You can see that the static route and the two routing information configured in Nacos are displayed side by side.

Modify Nacos configuration to turn off csdn routing

Refresh to view the routing information of the gateway

The routing of csdn is no longer visible, so it is possible to change the routing configuration dynamically.

This is the answer to the question about the dynamic routing of Spring Cloud Zuul and the example analysis of the integrated Nacos implementation. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel for more related knowledge.

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