In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the relevant knowledge of "how to achieve zuul dynamic routing". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Zuul dynamic routing
The gateway service is the only entry for traffic. You can't stop service at will. Therefore, dynamic routing is particularly necessary.
Database dynamic routing hot modifies the routing properties of zuul based on the event refresh mechanism.
DiscoveryClientRouteLocator
You can see that DiscoveryClientRouteLocator is the default refresh core processing class.
/ / reload the routing information method protected method. A submethod is required to redo the method. Protected LinkedHashMap locateRoutes () / / the method that triggers the refresh. RefreshableRouteLocator interface public void refresh () {this.doRefresh ();}
Both methods inherit from the SimpleRouteLocator class and reoperate. In fact, the official method notes indicate. If you need to read the load mapping relationship dynamically. These two methods need to be overridden by subclasses. Carry on the concrete realization
First of all, the pom jar package import requires a connection to the mysql database
Mysql mysql-connector-java org.springframework.boot spring-boot-starter-jdbc
Routing entity ZuulRouteEntity
Package com.xian.cloud.entity;import lombok.Data;import java.io.Serializable;import java.util.Date;/** * routing entity class * * @ author xianliru@100tal.com * @ version 1.0 * @ createDate 2019-10-30 15:00 * / @ Datapublic class ZuulRouteEntity implements Serializable {private static final long serialVersionUID = 1L; / * * router Id * / private Integer id / * routing path * / private String path; / * * Service name * / private String serviceId; / * url proxy * / private String url; / * forward and remove the prefix * / private String stripPrefix; / * * whether to retry * / private String retryable / * * whether to enable * / private String enabled; / * * sensitive request header * / private String sensitiveheadersList; / * creation time * / private Date createTime; / * Update time * / private Date updateTime / * Delete identity (0-normal, 1-delete) * / private String delFlag;}
The parent interface of the newly created DiscoveryRouteLocator class remains unchanged.
Package com.xian.cloud.router;import com.google.common.base.Strings;import com.google.common.collect.Sets;import com.xian.cloud.entity.ZuulRoute;import lombok.extern.slf4j.Slf4j;import org.springframework.cloud.netflix.zuul.filters.RefreshableRouteLocator;import org.springframework.cloud.netflix.zuul.filters.SimpleRouteLocator;import org.springframework.cloud.netflix.zuul.filters.ZuulProperties;import org.springframework.jdbc.core.BeanPropertyRowMapper;import org.springframework.jdbc.core.JdbcTemplate;import org.springframework.util.StringUtils Import java.util.*;/** @ author xianliru@100tal.com * @ version 1.0 * @ createDate 18:57 on 2019-10-30 * / @ Slf4jpublic class DiscoveryRouteLocator extends SimpleRouteLocator implements RefreshableRouteLocator {private ZuulProperties properties; private JdbcTemplate jdbcTemplate; public DiscoveryRouteLocator (String servletPath, ZuulProperties properties, JdbcTemplate jdbcTemplate) {super (servletPath, properties); this.properties = properties; this.jdbcTemplate = jdbcTemplate; log.info ("servletPath: {}", servletPath) } @ Override public void refresh () {doRefresh ();} @ Override protected Map locateRoutes () {LinkedHashMap routesMap = new LinkedHashMap (); / / load routing information routesMap.putAll (super.locateRoutes ()) from configuration file; / / Custom load routing information routesMap.putAll (getRouteList ()) / / 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;} / * read zuul routing rules from the database * @ return * / private LinkedHashMap getRouteList () {LinkedHashMap zuulRoutes = new LinkedHashMap () List sysZuulRoutes = jdbcTemplate.query ("select * from sys_zuul_route where del_flag = 0", new BeanPropertyRowMapper (ZuulRoute.class)); for (ZuulRoute route: sysZuulRoutes) {/ / empty skip if (Strings.isNullOrEmpty (route.getPath ()) & & Strings.isNullOrEmpty (route.getUrl () {continue;} ZuulProperties.ZuulRoute zuulRoute = new ZuulProperties.ZuulRoute () Try {zuulRoute.setId (route.getServiceId ()); zuulRoute.setPath (route.getPath ()); zuulRoute.setServiceId (route.getServiceId ()); zuulRoute.setRetryable (Objects.equals ("0", route.getRetryable ())? Boolean.FALSE: Boolean.TRUE); zuulRoute.setStripPrefix (Objects.equals ("0", route.getStripPrefix ())? Boolean.FALSE: Boolean.TRUE); zuulRoute.setUrl (route.getUrl ()); List sensitiveHeadersList = Arrays.asList (route.getSensitiveheadersList (). Split (",")); if (sensitiveHeadersList! = null) {Set sensitiveHeaderSet = Sets.newHashSet (); sensitiveHeadersList.forEach (sensitiveHeader-> sensitiveHeaderSet.add (sensitiveHeader)); zuulRoute.setSensitiveHeaders (sensitiveHeaderSet) ZuulRoute.setCustomSensitiveHeaders (true);}} catch (Exception e) {log.error ("Database loading configuration exception", e);} log.info ("Custom routing configuration, path: {}, serviceId: {}", zuulRoute.getPath (), zuulRoute.getServiceId ()) ZuulRoutes.put (zuulRoute.getPath (), zuulRoute);} return zuulRoutes;}}
We also need a direct diagram of the producer and consumer of the event to facilitate integration into a class
Package com.xian.cloud.event;import com.xian.cloud.router.DiscoveryRouteLocator;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.cloud.client.discovery.event.HeartbeatEvent;import org.springframework.cloud.client.discovery.event.HeartbeatMonitor;import org.springframework.cloud.context.scope.refresh.RefreshScopeRefreshedEvent;import org.springframework.cloud.netflix.zuul.RoutesRefreshedEvent;import org.springframework.cloud.netflix.zuul.web.ZuulHandlerMapping;import org.springframework.context.ApplicationEvent;import org.springframework.context.ApplicationEventPublisher Import org.springframework.context.ApplicationListener;import org.springframework.context.event.ContextRefreshedEvent;import org.springframework.stereotype.Service;/** * routing refresh event release, with event listeners * * @ author xianliru@100tal.com * @ version 1.0 * @ createDate 15:27 on 2019-10-30 * / @ Servicepublic class RefreshRouteService implements ApplicationListener {@ Autowired private ZuulHandlerMapping zuulHandlerMapping; private HeartbeatMonitor heartbeatMonitor = new HeartbeatMonitor (); @ Autowired ApplicationEventPublisher publisher; @ Autowired private DiscoveryRouteLocator dynamicRouteLocator / * dynamic routing implementation calls refreshRoute () to issue refresh routing events * / public void refreshRoute () {RoutesRefreshedEvent routesRefreshedEvent = new RoutesRefreshedEvent (dynamicRouteLocator); publisher.publishEvent (routesRefreshedEvent);} / * event listeners. Monitoring detects event refresh * @ param event * / @ Override public void onApplicationEvent (ApplicationEvent event) {if (event instanceof ContextRefreshedEvent | | event instanceof RefreshScopeRefreshedEvent | | event instanceof RoutesRefreshedEvent) {/ / active manual refresh. Context refresh, configuration property refresh zuulHandlerMapping.setDirty (true);} else if (event instanceof HeartbeatEvent) {/ / heartbeat trigger, will map the relationship locally. Associate to remote service HeartbeatEvent heartbeatEvent = (HeartbeatEvent) event; if (heartbeatMonitor.update (heartbeatEvent.getValue () {zuulHandlerMapping.setDirty (true);}
Provide trigger interface to the outside
Package com.xian.cloud.controller;import com.xian.cloud.event.RefreshRouteService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RestController;/** * manually refresh the external interface * * @ author xianliru@100tal.com * @ version 1.0 * @ createDate 20:23 on 2019-10-30 * / @ RestControllerpublic class RefreshController {@ Autowired private RefreshRouteService refreshRouteService @ GetMapping ("/ refresh") public String refresh () {refreshRouteService.refreshRoute (); return "refresh";}}
Database table structure
CREATE TABLE `sys_zuul_ route` (`id`int (11) NOT NULL AUTO_INCREMENT COMMENT 'router Id', `path` NOT NULL COMMENT' routing path', `service_ id`NOT NULL COMMENT 'service name', `url`varchar (255) DEFAULT NULL COMMENT 'url proxy', `strip_ prefix`char (1) DEFAULT'1' COMMENT 'forward remove prefix', `retryable`char (1) DEFAULT'1' COMMENT 'whether to retry', `enabled` char (1) DEFAULT'1' COMMENT'is enabled or not `del_ list`varchar (255) DEFAULT NULL COMMENT 'sensitive request header', `create_ time`timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'creation time', `update_ time`timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT 'update time', `del_ list`char (1) DEFAULT'0' COMMENT 'delete identity (0-normal, 1-delete)', PRIMARY KEY (`id`) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8mb4 ROW_FORMAT=DYNAMIC COMMENT=' dynamic routing configuration table'
Comment out the configuration file client Consumer Service routing configuration. Set up the data source. Read from the database
Start the service to print logs
2019-10-30 20 c.xian.cloud.router.DynamicRouteLocator 49 INFO 39.946 INFO 63449-[TaskScheduler-1] c.xian.cloud.router.DynamicRouteLocator: add a custom routing configuration for the database, path:/client/**,serviceId:cloud-discovery-client2019-10-30 20 path:/client/**,serviceId:cloud-discovery-client2019 40.397 INFO 63449-[TaskScheduler-1] c.xian.cloud.router.DynamicRouteLocator: add a custom routing configuration for the database, path:/client/**,serviceId:cloud-discovery-client
Postman requests the client interface to see if it can be forwarded successfully.
Based on zuul dynamic gateway routing is completed.
This is the end of the content of "how to achieve zuul dynamic routing". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.