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 > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces how to use nacos gateway dynamic routing, the article is very detailed, has a certain reference value, interested friends must read it!
Nacos gateway dynamic routing
Note: the gateway used in this test is 2.2.2.RELEASE, and other versions may be different.
I. Introduce the pom dependency org.springframework.cloud spring-cloud-starter-gateway com.alibaba.cloud spring-cloud-starter-alibaba-nacos-config com.alibaba.cloud spring-cloud-starter-alibaba-nacos-discovery required for this test Com.alibaba fastjson 1.2.47 II. Configuration file settings (* change the name to bootstrap.yml if the configuration file is not valid) server: port: 8200 spring: application: name: lc-gateway cloud: nacos: discovery: # Registry address server-addr: 106.12.146.239 spring 8848 config: server-addr: 106.12.146.239 spring 8848 # configuration Center-specify a blank name Namespace: bb79a8c4-e4e1-4a27-bceb-0810f278b5aa # specify configuration file suffix file-extension: yaml # configuration group group: DEFAULT_GROUP # configuration dateId data-id: lc-gateway # get configuration timeout timeout: 5000 gateway: # set timeout default httpclient: connect-timeout: 1000 response-timeout: 5s
Ps: here is an integrated nacos configuration center. For more information, please go to the spring cloud Integrated nacos configuration Center.
Third, dynamic routing to achieve package com.lc.api.gateway.config; import com.alibaba.fastjson.JSONObject;import com.alibaba.nacos.api.NacosFactory;import com.alibaba.nacos.api.config.ConfigService;import com.alibaba.nacos.api.config.listener.Listener;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Value;import org.springframework.cloud.gateway.event.RefreshRoutesEvent Import org.springframework.cloud.gateway.route.RouteDefinition;import org.springframework.cloud.gateway.route.RouteDefinitionWriter;import org.springframework.context.ApplicationEventPublisher;import org.springframework.context.ApplicationEventPublisherAware;import org.springframework.stereotype.Service;import reactor.core.publisher.Mono; import javax.annotation.PostConstruct;import java.util.ArrayList;import java.util.List;import java.util.Properties;import java.util.concurrent.Executor / * dynamic routing, which can be done only by obtaining Bean. Add, delete, modify and query released features * * @ Author: lc * @ Date: 15:49 * / @ Servicepublic class DynamicRouteConfig implements ApplicationEventPublisherAware {private static final Logger logger = LoggerFactory.getLogger (DynamicRouteConfig.class) on 2020-7-8; @ Autowired private RouteDefinitionWriter routedefinitionWriter; private ApplicationEventPublisher publisher; @ Value ("${spring.cloud.nacos.config.data-id}") private String dataId @ Value ("${spring.cloud.nacos.config.group}") private String group; @ Value ("${spring.cloud.nacos.config.server-addr}") private String serverAddr; @ Value ("${spring.cloud.nacos.config.namespace}") private String namespace; @ Value ("${spring.cloud.nacos.config.timeout}") private long timeout; private static final List ROUTE_LIST = new ArrayList () PostConstruct public void dynamicRouteByNacosListener () {try {Properties prop = new Properties (); prop.put ("serverAddr", serverAddr); prop.put ("namespace", namespace); ConfigService config = NacosFactory.createConfigService (prop); String content = config.getConfig (dataId, group, timeout); publisher (content) Config.addListener (dataId, group, new Listener () {@ Override public void receiveConfigInfo (String config) {publisher (config);} @ Override public Executor getExecutor () {return null;}}) } catch (Exception e) {e.printStackTrace ();} / * * add routing * * @ param def * @ return * / public Boolean addRoute (RouteDefinition def) {try {routedefinitionWriter.save (Mono.just (def)) .subscribe (); ROUTE_LIST.add (def.getId ()) } catch (Exception e) {e.printStackTrace ();} return true;} / * * Delete route * * @ return * / public Boolean clearRoute () {for (String id: ROUTE_LIST) {routedefinitionWriter.delete (Mono.just (id)). Subscribe ();} ROUTE_LIST.clear () Return Boolean.FALSE;} / * publish routing * / private void publisher (String config) {clearRoute (); try {logger.info ("Start updating dynamic routing...."); List routeDefinitionList = JSONObject.parseArray (config, RouteDefinition.class) For (RouteDefinition route: routeDefinitionList) {logger.info (route.toString ()); addRoute (route);} publisher.publishEvent (new RefreshRoutesEvent (this.routedefinitionWriter)); logger.info ("update completed");} catch (Exception e) {logger.error ("Failed to update routing information", e) E.printStackTrace ();} @ Override public void setApplicationEventPublisher (ApplicationEventPublisher applicationEventPublisher) {publisher = applicationEventPublisher;}} IV. Nacos configuration center settings
1. Description
two。 Create a new gateway configuration
3. Add the configuration in the following format
I won't comment here. Everyone should be able to understand it.
[{"filters": [{"args": {"parts": "1"}, "name": "StripPrefix"}], "id": "authent1", "order":-1 "predicates": [{"args": {"pattern": "/ authent/**"}, "name": "Path"}], "uri": "lb://lc-authenticate"}] V. Test
Configuration related to gateway Gateway
Create, using initilizer
Group:com.atguigu.gulimall
Artifact: gulimall-gateway
Package:com.atguigu.gulimall.gateway
Search for gateway selected.
Add common dependency to pom.xml to modify the jdk version
Add an annotation @ EeableDiscoveryClient to the startup class
Configure the nacos registry address spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848spring.application.name=gulimall-gatewayserver.port=88bootstrap.properties fill in the configuration center address spring.application.name=gulimall-gatewayspring.cloud.nacos.config.server-addr=127.0.0.1:8848spring.cloud.nacos.config.namespace=ab66aff2-0bd5-4f80-8a68-760d6ff7d96dnacos to create the namespace gateway
Then create the file guilmall-gateway.yml in the namespace
Spring: application: name: gulimall-gateway shields the data source in the main class
Create application.ymlspring: cloud: gateway: routes:-id: after_route uri: https://www.xiaomi.com predicates:-Query=url,xiaomi# in the project and jump to the specified uri if the parameter is equal to the assertion
Running result
The above is all the contents of the article "how to use nacos gateway dynamic routing". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!
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.