nacos gateway动态路由

Posted java架构宝典

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了nacos gateway动态路由相关的知识,希望对你有一定的参考价值。

*说明:本次测试使用的gateway是2.2.2.RELEASE版本,其他版本可能存在不同

一、引入本次测试需要的pom依赖


  
    
    
  
  1. <!--gateway网关依赖-->

  2. <dependency>

  3. <groupId>org.springframework.cloud</groupId>

  4. <artifactId>spring-cloud-starter-gateway</artifactId>

  5. </dependency>

  6. <!--nacos依赖-->

  7. <dependency>

  8. <groupId>com.alibaba.cloud</groupId>

  9. <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>

  10. </dependency>

  11. <dependency>

  12. <groupId>com.alibaba.cloud</groupId>

  13. <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>

  14. </dependency>

  15. <!--json工具包-->

  16. <dependency>

  17. <groupId>com.alibaba</groupId>

  18. <artifactId>fastjson</artifactId>

  19. <version>1.2.47</version>

  20. </dependency>

二、配置文件设置(*配置文件不生效的把名字改为bootstrap.yml


  
    
    
  
  1. server:

  2. port: 8200

  3. spring:

  4. application:

  5. name: lc-gateway

  6. cloud:

  7. nacos:

  8. discovery:

  9. server-addr: 106.12.146.239:8848

  10. config:

  11. server-addr: 106.12.146.239:8848

  12. # 配置中心-指定命名空间

  13. namespace: bb79a8c4-e4e1-4a27-bceb-0810f278b5aa

  14. # 指定配置文件后缀

  15. file-extension: yaml

  16. #配置组

  17. group: DEFAULT_GROUP

  18. #配置dateId

  19. data-id: lc-gateway

  20. #获取配置超时时间

  21. timeout: 5000

  22. gateway:

  23. #设置超时时间默认

  24. httpclient:

  25. connect-timeout: 1000

  26. response-timeout: 5s

ps:这里集成了nacos配置中心想了解详情请移步spring cloud集成nacos配置中心

三、动态路由实现


  
    
    
  
  1. package com.lc.api.gateway.config;

  2. import com.alibaba.fastjson.JSONObject;

  3. import com.alibaba.nacos.api.NacosFactory;

  4. import com.alibaba.nacos.api.config.ConfigService;

  5. import com.alibaba.nacos.api.config.listener.Listener;

  6. import org.slf4j.Logger;

  7. import org.slf4j.LoggerFactory;

  8. import org.springframework.beans.factory.annotation.Autowired;

  9. import org.springframework.beans.factory.annotation.Value;

  10. import org.springframework.cloud.gateway.event.RefreshRoutesEvent;

  11. import org.springframework.cloud.gateway.route.RouteDefinition;

  12. import org.springframework.cloud.gateway.route.RouteDefinitionWriter;

  13. import org.springframework.context.ApplicationEventPublisher;

  14. import org.springframework.context.ApplicationEventPublisherAware;

  15. import org.springframework.stereotype.Service;

  16. import reactor.core.publisher.Mono;

  17. import javax.annotation.PostConstruct;

  18. import java.util.ArrayList;

  19. import java.util.List;

  20. import java.util.Properties;

  21. import java.util.concurrent.Executor;

  22. /**

  23. * 动态路由,可以通过获取Bean才做该类,提供增删改查已经发布功能

  24. *

  25. * @Author: lc

  26. * @Date: 2020/7/8 15:49

  27. */

  28. @Service

  29. public class DynamicRouteConfig implements ApplicationEventPublisherAware {

  30. private static final Logger logger = LoggerFactory.getLogger(DynamicRouteConfig.class);

  31. @Autowired

  32. private RouteDefinitionWriter routedefinitionWriter;

  33. private ApplicationEventPublisher publisher;

  34. @Value("${spring.cloud.nacos.config.data-id}")

  35. private String dataId;

  36. @Value("${spring.cloud.nacos.config.group}")

  37. private String group;

  38. @Value("${spring.cloud.nacos.config.server-addr}")

  39. private String serverAddr;

  40. @Value("${spring.cloud.nacos.config.namespace}")

  41. private String namespace;

  42. @Value("${spring.cloud.nacos.config.timeout}")

  43. private long timeout;

  44. private static final List<String> ROUTE_LIST = new ArrayList<>();

  45. @PostConstruct

  46. public void dynamicRouteByNacosListener() {

  47. try {

  48. Properties prop = new Properties();

  49. prop.put("serverAddr", serverAddr);

  50. prop.put("namespace", namespace);

  51. ConfigService config = NacosFactory.createConfigService(prop);

  52. String content = config.getConfig(dataId, group, timeout);

  53. publisher(content);

  54. config.addListener(dataId, group, new Listener() {

  55. @Override

  56. public void receiveConfigInfo(String config) {

  57. publisher(config);

  58. }

  59. @Override

  60. public Executor getExecutor() {

  61. return null;

  62. }

  63. });

  64. } catch (Exception e) {

  65. e.printStackTrace();

  66. }

  67. }

  68. /**

  69. * 增加路由

  70. *

  71. * @param def

  72. * @return

  73. */

  74. public Boolean addRoute(RouteDefinition def) {

  75. try {

  76. routedefinitionWriter.save(Mono.just(def)).subscribe();

  77. ROUTE_LIST.add(def.getId());

  78. } catch (Exception e) {

  79. e.printStackTrace();

  80. }

  81. return true;

  82. }

  83. /**

  84. * 删除路由

  85. *

  86. * @return

  87. */

  88. public Boolean clearRoute() {

  89. for (String id : ROUTE_LIST) {

  90. routedefinitionWriter.delete(Mono.just(id)).subscribe();

  91. }

  92. ROUTE_LIST.clear();

  93. return Boolean.FALSE;

  94. }

  95. /**

  96. * 发布路由

  97. */

  98. private void publisher(String config) {

  99. clearRoute();

  100. try {

  101. logger.info("Start updating dynamic routing ....");

  102. List<RouteDefinition> routeDefinitionList = JSONObject.parseArray(config, RouteDefinition.class);

  103. for (RouteDefinition route : routeDefinitionList) {

  104. logger.info(route.toString());

  105. addRoute(route);

  106. }

  107. publisher.publishEvent(new RefreshRoutesEvent(this.routedefinitionWriter));

  108. logger.info("update completed ");

  109. } catch (Exception e) {

  110. logger.error("Failed to update routing information", e);

  111. e.printStackTrace();

  112. }

  113. }

  114. @Override

  115. public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {

  116. publisher = applicationEventPublisher;

  117. }

  118. }

 

四、nacos配置中心设置

   1.说明

  2.新建一个网关配置

nacos gateway动态路由

  3. 添加配置格式如下

nacos gateway动态路由

 这里我就不注释了大家应该都能看懂 


  
    
    
  
  1. [

  2. {

  3. "filters": [

  4. {

  5. "args": {

  6. "parts": "1"

  7. },

  8. "name": "StripPrefix"

  9. }

  10. ],

  11. "id": "authent1",

  12. "order": -1,

  13. "predicates": [

  14. {

  15. "args": {

  16. "pattern": "/authent/**"

  17. },

  18. "name": "Path"

  19. }

  20. ],

  21. "uri": "lb://lc-authenticate"

  22. }

  23. ]

 五、测试

nacos gateway动态路由







nacos gateway动态路由

点亮 ,告诉大家你也在看

以上是关于nacos gateway动态路由的主要内容,如果未能解决你的问题,请参考以下文章

Nacos + Gateway 实现动态刷新路由

Nacos + Gateway 实现动态刷新路由

Spring Gateway集成nacos实现动态路由配置

nacos gateway动态路由

spring-gateway基于数据库 + nacos 的动态路由

关于Spring cloud Gateway集成nacos 实现路由到指定微服务的方式总结