spring cloud gateway和nacos整合

spring cloud gateway和nacos整合

期望结果:

  1. 通过输入http://127.0.0.1:8080/first,跳到哔哩哔哩主页。然后通过修改nacos的配置中心里面gateway的配置,使得再次输入地址,跳到百度主页
  2. 整合nacos和spring cloud gateway。使得spring cloud gateway能读取到naco的服务注册信息,通过这些服务注册信息进行分发。

spring cloud gateway配置

yml依赖:

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
            <version>0.9.0.RELEASE</version>
        </dependency>


        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
            <version>0.9.0.RELEASE</version>
        </dependency>
    </dependencies>

注意:Hoxton.SR4这个版本是需要添加spring-boot-starter-validation的,不然会报错的。其他版本不清楚会不会

bootstrap.yml配置:

spring:
  application:
    name: gateway-nacos
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848  
        enabled: true
      config:
        file-extension: yaml
        server-addr: 127.0.0.1:8848
server:
  port: 8080

java代码实现:

启动类:

@SpringBootApplication
@EnableDiscoveryClient //开启服务注册
public class NacosGatewayApp {

    public static void main(String[] args) {
        SpringApplication.run(NacosGatewayApp.class,args);
    }
}

nacos动态路由实现类:

/**
 * @Author: gyc
 * @Date: 2020/12/4 16:18
 */
@Component
public class NacosRouteDefinitionRepository implements RouteDefinitionRepository , ApplicationContextAware {


    @Autowired
    private NacosConfigProperties nacosConfigProperties;


    private String dataId = "gatewayId";

    private String groupId = "gatewayGroup";


    public Flux<RouteDefinition> getRouteDefinitions() {
        List<RouteDefinition> list = new ArrayList();
        try {
            //获取组名是gatewayGroup,dataId是gatewayId的配置。5000代表超时时间
            String  content = nacosConfigProperties.configServiceInstance().getConfig(dataId,groupId,5000);

            List<RouteDefinition> tmpList = JSONObject.parseArray(content, RouteDefinition.class);
            if(tmpList != null){
                list = tmpList;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return Flux.fromIterable(list);
    }

    public Mono<Void> save(Mono<RouteDefinition> route) {
        return null;
    }

    public Mono<Void> delete(Mono<String> routeId) {
        return null;
    }


    /**
     * 项目启动的时候会触发这个方法。
     * 方法实现: 监听节点的变化,如果节点变化就发送RefreshRoutesEvent事件。
     * gateway收到RefreshRoutesEvent事件的话,就会触发getRouteDefinitions方法了
     * @param applicationContext
     * @throws BeansException
     */
    public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException {

        try {
            nacosConfigProperties.configServiceInstance().addListener(dataId, groupId, new Listener() {
                public Executor getExecutor() {
                    return null;
                }

                public void receiveConfigInfo(String s) {
                    //如果节点变化就发送RefreshRoutesEvent事件。
                    applicationContext.publishEvent(new RefreshRoutesEvent(this));
                }
            });
        } catch (NacosException e) {
            e.printStackTrace();
        }
    }
}

整体实现:

  • 因为NacosRouteDefinitionRepository实现了ApplicationContextAware接口,所以项目启动的时候会触发setApplicationContext方法。

  • setApplicationContext: 监听节点的变化,如果节点变化就发送RefreshRoutesEvent事件。

  • gateway收到RefreshRoutesEvent事件的话,就会触发getRouteDefinitions方法了(这里需要实现RouteDefinitionRepository接口,才会触发方法)

下面在下个图就是程序的走向。

gateway和nacos整合

nacos-client的配置

yml的依赖:

    <dependencies>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
            <version>0.9.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

application.yml配置文件:

server:
  port: 8061
spring:
  application:
    name: nacos-client
  cloud:
    nacos:
      discovery:
        register-enabled: true
        server-addr: 127.0.0.1:8848


代码实现:

/**
 * @author gyc
 * @date 2020/12/6
 */
@SpringBootApplication
@EnableDiscoveryClient
public class NacosClientApp {

    public static void main(String[] args) {
        SpringApplication.run(NacosClientApp.class,args);
    }

}

@RestController
@RequestMapping
public class HelloController {
    
    @GetMapping("/sayHello")
    public String sayHello(){
        return "sayHello";
    }
    
}

nacos的一些配置

​ 由上面的gateway的配置来看,我们是没有给gateway配置路由信息的。这时候我们是要通过nacos的统一的配置中心来做个配置。

注意: 我们这个是通过读取json的方式,来做解析的,这里断言和过滤器的的配置方式需要是使用Fully Expanded Arguments

可以看会我之前的有一篇叫做Spring Cloud Gateway入门demo博文里面的断言和过滤器配置方式章节,地址如下:

https://www.cnblogs.com/dabenxiang/p/13778128.html

新增一个配置信息:

image-20201208104613581

配置内容如下:

[{
  "id": "first_route",
  "predicates": [{
    "name": "Path",
    "args": {"_genkey_0":"/first"}
  }],
  "filters": [{
      "name" : "StripPrefix",
      "args":{"parts":"1"}
  }],
  "uri": "https://www.bilibili.com/",
  "order": 0
},
{
  "id":"nacos-client",
   "predicates": [{
    "name": "Path",
    "args": {"_genkey_0":"/nacos/**"}
  }],
   "filters": [{
      "name" : "StripPrefix",
      "args":{"parts":"1"}
  }],
  "uri": "lb://nacos-client",
  "order": 0
}
]

这个配置包括两个路由的信息

  • 第一个路由first_route: 当输入127.0.0.1:8080/first_route 路径的时候会跳到https://www.bilibili.com/页面
  • 第二个路由nacos-client: 当输入127.0.0.1:8080/nacos/say/**的路径的时候会跳到lb://nacos-client/**页面。

效果展示

通过输入http://127.0.0.1:8080/first,跳到哔哩哔哩主页。然后通过修改nacos的配置中心里面gateway的配置,使得再次输入地址,跳到百度主页

gatewayAndNacos20201209

如果加载不出gif图请访问:https://gitee.com/gzgyc/blogimage/raw/master/gatewayAndNacos20201209.gif

原文地址:https://www.cnblogs.com/dabenxiang/p/14376575.html