跳至主要內容

SpringCloud教程第7篇:使用spring cloud gateway作为服务网关

Mr.DabaoSpringCloud约 514 字大约 2 分钟

使用spring cloud gateway作为服务网关

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

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

工程构建

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

image-20221109204149874

gateway需要注册到nacos中去,需要引入以下的依赖:

        <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文件:

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

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

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

 @SpringBootApplication
@EnableDiscoveryClient
public class GatewayApplication {

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

}

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

img
img

在浏览器上输入http://localhost:5000/consumer/hi-feign,浏览器返回响应:open in new window

hello feign, i'm provider ,my port:8762

gateway还有其他很多强大的功能在这里就不再讲述。

相关教程