spring cloud 集成 gateway

319 阅读1分钟

spring cloud 集成 gateway

  • 导入spring cloud gateway 得mavenyilai
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-gateway-core</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-webflux</artifactId>
</dependency>

gateway是基于webflux开发得网关组件,所以需要引入webflux依赖

  • 创建bootstrap.yml配置文件

image.png

我是基于spring cloud alibaba nacos 注册中心以及spring cloud alibaba config配置中心,所以我得配置文件要需要优先于application.yml,因此我创建得是bootstrap.yml

  • 配置nacos地址以及配置中心地址和规则
server:
  port: 9001
spring:
  application:
    name: @artifactId@             #服务名称
  profiles:
    active: @profiles.active@      #当前环境
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848   #nacos服务端地址
      config:
        server-addr: 127.0.0.1:8848   #nacos配置中心地址
        file-extension: yml               #nacos配置中心配置文件后缀
        shared-configs:                   #读取以下名称的配置文件,可配置多个文件
          - ${spring.application.name}-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension}
  • 配置中心配置文件
spring:
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true                   #开启动态路由,支持服务名称做地址
      routes:                             #路由规则
        - id: lw-stock-biz                #路由id 一般用服务名称做id
          uri: lb://lw-stock-biz          #路由地址
          predicates:                     #断言
            - Path=/stock/**              #以/stock开头得都走这个路由
          filters:                        #过滤器
            - StripPrefix=1               #截取路径地址,/stock/goods/detail 截取后就是 /goods/detail
        - id: lw-sys-biz
          uri: lb://lw-sys-biz
          predicates:
            - Path=/sys/**
          filters:
            - StripPrefix=1