SpringCloud 2020版本教程2:使用spring cloud gateway做为服务网关

Spring Cloud Gateway是Spring Cloud官方推出的第二代网关框架,取代Zuul网关。网关做为流量的,在微服务系统中有着很是做用,网关常见的功能有路由转发、权限校验、限流控制等做用。html

在上一节的案例中,咱们讲述了如何使用nacos做为服务注册中心和配置中心,使用feign和sc loadbalancer做为服务调用。本小节将讲述如何使用spring cloud gateway做为服务网关。git

工程构建

新建一个gateway的工程,工程目录以下:github

gateway须要注册到nacos中去,须要引入如下的依赖:web

<dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>

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

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-loadbalancer</artifactId>
        </dependency>
        
复制代码

在配置文件application.pom文件:spring

server:
  port: 5000

spring:
  application:
    name: gateway
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848
    gateway:
      discovery:
        locator:
          enabled: false
          lowerCaseServiceId: true
      routes:
        - id: provider
          uri: lb://provider
          predicates:
            - Path=/provider/**
          filters:
            - StripPrefix=1
        - id: consumer
          uri: lb://consumer
          predicates:
            - Path=/consumer/**
          filters:
            - StripPrefix=1

复制代码

配置的解释请阅读文末的相关教程,在这里再也不重复。浏览器

在工程的启动文件加上相关注解:markdown

@SpringBootApplication
@EnableDiscoveryClient
public class GatewayApplication {

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

}
复制代码

依次启动gateway\consumer\provider三个工程,在nacos中已经成功注册:app

在浏览器上输入http://localhost:5000/consumer/hi-feign,浏览器返回响应:框架

hello feign, i'm provider ,my port:8762
复制代码

gateway还有其余不少强大的功能在这里就再也不讲述。ide

相关教程

源码下载

github.com/forezp/Spri…

相关文章
相关标签/搜索