欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

nacos gateway动态路由实战

程序员文章站 2022-03-07 22:52:43
目录在启动类中添加注解@eeablediscoveryclientnacos gateway动态路由说明:本次测试使用的gateway是2.2.2.release版本,其他版本可能存在不同一、引入本次...

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配置中心想了解详情请移步

三、动态路由实现

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.说明

nacos gateway动态路由实战

2.新建一个网关配置

nacos gateway动态路由实战

3. 添加配置格式如下

nacos gateway动态路由实战

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

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

五、测试

nacos gateway动态路由实战

gateway网关相关配置

创建,使用initilizer,

  • group:com.atguigu.gulimall
  • artifact: gulimall-gateway
  • package:com.atguigu.gulimall.gateway

搜索gateway选中。

pom.xml里加上common依赖, 修改jdk版本

在启动类中添加注解@eeablediscoveryclient

nacos gateway动态路由实战

配置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

在主类中屏蔽数据源

nacos gateway动态路由实战

在项目里创建application.yml

spring:
  cloud:
    gateway:
      routes:
        - id: after_route
          uri: https://www.xiaomi.com
          predicates:
            - query=url,xiaomi
#            若参数等于断言 则跳转到指定的uri

运行结果

nacos gateway动态路由实战

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。