暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

Spring Cloud Gateway教程[一]:Gateway与Eureka整合

CodingWithFun 2019-08-21
1529


简介

spring cloud gateway提供了API网关功能,建立在Spring生态体系之上,包括Spring 5, Spring Boot 2和Reactor项目。Gateway是Spring Cloud推出的第二代网关,使用非阻塞API,用于取代Zuul网关。本文用案例的形式让大家体验一下Gateway环境的搭建。本文所有代码放在:https://github.com/loveoobaby/blog_code/tree/master/spring_gateway


准备注册中心Eureka

Eureka启动比较简单,只需添加对应的依赖,写一个入口Application类,添加@EnableEurekaServer即可,代码如下,不过多解释。

1<dependencies>
2    <dependency>
3        <groupId>org.springframework.cloud</groupId>
4        <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
5    </dependency>
6</dependencies>


1@EnableEurekaServer
2@SpringBootApplication
3public class EurekaServerApplication {
4
5    public static void main(String[] args) {
6        SpringApplication.run(EurekaServerApplication.class, args);
7    }
8}


准备网关服务
gateway需要依赖spring-cloud-starter-gateway,同时要让网关注册到注册中心,故需要添加eureka client依赖。
 1<dependencies>
2    <dependency>
3        <groupId>org.springframework.cloud</groupId>
4        <artifactId>spring-cloud-starter-gateway</artifactId>
5    </dependency>
6
7    <dependency>
8        <groupId>org.springframework.cloud</groupId>
9        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
10    </dependency>
11</dependencies>


修改application.yaml配置文件如下:

    server:
    port: 8080
    spring:
    application:
    name: cloud-gateway-demo
    cloud:
    gateway:
    discovery:
    locator:
    enabled: true


    eureka:
    client:
    service-url:
    defaultZone: http://localhost:8761/eureka/

    Gateway可以与服务发现整合,通过url中的服务名与注册中心的服务名进行匹配来路由转发。启用方式是spring.cloud.gateway.discovery.locator.

    enabled=true。


    测试

    测试网关我们需要在启动一个服务,让其注册到Eureka。网关如果可以代理的话,相对于会直接访问服务,url会有对应的改变:

      原url: http://原服务地址:端口/{controller路径}
      新url: http://网关地址:端口/{注册中心server id}/{controller路径}

      如果新url工作正常,说明网关搭建成功。


      躺过的坑

      这里要注意的坑是应用的名称不能用下划线,使用下划线网关代理不了,中划线没有问题。注册Eureka时,server id默认就是application.name,说明gateway不能代理含下划线的server id。

        spring:
        application:
            name: server_demo

        具体原因以后分析一下源码再来讲解。

        文章转载自CodingWithFun,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

        评论