nacos gateway動態路由實戰

nacos gateway動態路由

說明:本次測試使用的gateway是2.2.2.RELEASE版本,其他版本可能存在不同

一、引入本次測試需要的pom依賴

       <!--gateway網關依賴-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>
        <!--nacos依賴-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
        <!--json工具包-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.47</version>
        </dependency>

二、配置文件設置(*配置文件不生效的把名字改為bootstrap.yml)

server:
  port: 8200
 
spring:
  application:
    name: lc-gateway
 
  cloud:
    nacos:
      discovery:
        #註冊中心地址
        server-addr: 106.12.146.239:8848
      config:
        server-addr: 106.12.146.239:8848
        # 配置中心-指定命名空間
        namespace: bb79a8c4-e4e1-4a27-bceb-0810f278b5aa
        # 指定配置文件後綴
        file-extension: yaml
        #配置組
        group: DEFAULT_GROUP
        #配置dateId
        data-id: lc-gateway
        #獲取配置超時時間
        timeout: 5000
 
    gateway:
      #設置超時時間默認
      httpclient:
        connect-timeout: 1000
        response-timeout: 5s

ps:這裡集成瞭nacos配置中心想瞭解詳情請移步spring cloud集成nacos配置中心

三、動態路由實現

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;
 
/**
 * 動態路由,可以通過獲取Bean才做該類,提供增刪改查已經發佈功能
 *
 * @Author: lc
 * @Date: 2020/7/8 15:49
 */
@Service
public class DynamicRouteConfig implements ApplicationEventPublisherAware { 
    private static final Logger logger = LoggerFactory.getLogger(DynamicRouteConfig.class); 
    @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<String> 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();
        }
    }
 
    /**
     * 增加路由
     *
     * @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;
    }
 
    /**
     * 刪除路由
     *
     * @return
     */
    public Boolean clearRoute() {
        for (String id : ROUTE_LIST) {
            routedefinitionWriter.delete(Mono.just(id)).subscribe();
        }
        ROUTE_LIST.clear();
        return Boolean.FALSE;
    }
 
    /**
     * 發佈路由
     */
    private void publisher(String config) {
        clearRoute();
        try {
            logger.info("Start updating dynamic routing ....");
            List<RouteDefinition> 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;
    } 
}

四、nacos配置中心設置

1.說明

2.新建一個網關配置

3. 添加配置格式如下

這裡我就不註釋瞭大傢應該都能看懂

[
    {
        "filters": [
            {
                "args": {
                    "parts": "1"
                },
                "name": "StripPrefix"
            }
        ],
        "id": "authent1",
        "order": -1,
        "predicates": [
            {
                "args": {
                    "pattern": "/authent/**"
                },
                "name": "Path"
            }
        ],
        "uri": "lb://lc-authenticate"
    }
]

五、測試

gateway網關相關配置

創建,使用initilizer,

  • Group:com.atguigu.gulimall
  • Artifact: gulimall-gateway
  • package:com.atguigu.gulimall.gateway

搜索gateway選中。

pom.xml裡加上common依賴, 修改jdk版本

在啟動類中添加註解@EeableDiscoveryClient

在這裡插入圖片描述

配置nacos註冊中心地址

spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
spring.application.name=gulimall-gateway
server.port=88

bootstrap.properties 填寫配置中心地址

spring.application.name=gulimall-gateway
spring.cloud.nacos.config.server-addr=127.0.0.1:8848
spring.cloud.nacos.config.namespace=ab66aff2-0bd5-4f80-8a68-760d6ff7d96d

nacos裡創建命名空間gateway

然後在命名空間裡創建文件guilmall-gateway.yml

spring:
    application:
        name: gulimall-gateway

在主類中屏蔽數據源

在這裡插入圖片描述

在項目裡創建application.yml

spring:
  cloud:
    gateway:
      routes:
        - id: after_route
          uri: https://www.xiaomi.com
          predicates:
            - Query=url,xiaomi
#            若參數等於斷言 則跳轉到指定的uri

運行結果

在這裡插入圖片描述

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。

推薦閱讀: