API网关Gateway

1、导入依赖 (其中还是用了注册中心eureka和配置中心config,不用可以不导入)

    <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-config</artifactId>
        </dependency>

2、启动类添加注解(如果不用eureka和config的话可以不加)

@EnableEurekaClient
@EnableDiscoveryClient

3、YAML配置

spring:
  application:
    name: spring-cloud-gateway
  cloud:
    config:
      discovery:
        service-id: config-server
        enabled: true
      # 指定分支
      label: master
      # 如果使用了eureka就不需要配置config-server地址
      # uri: http://localhost:10021/
      name: config-server
      profile: gateway
    gateway:
      routes:
      - id: gateway1
        uri: lb://config-client
        predicates:
        - Path=/test/**
        filters:
        - RewritePath=/test/(?<segment>.*), /test/$\{segment}


eureka:
  client:
    service-url:
      defaultZone: http://{ip}:{port}/eureka/
server:
  port: 10031
management:
  endpoints:
    web:
      exposure:
        include: "*"

 

说明:id可以不用配置,默认是uuid,如果没有注册中心的话gateway.routes.uri应该修改成转发的地址例如:http://ip:port, 根据predicates中的配置匹配访问uri,然后根据filters修改访问条件,转发到uri上,这里就是如果访问的地址是http://ip:10031/test/any,转发后的地址就是http://{lb://config-client}/test/any

 

注意: 这里需要注意的是如果用了配置中心,别把配置中心需要覆盖的内容写到bootstrap.yml中,因为bootstrap.yml的优先级高于application.yml,而配置中心是与application进行合并生成一个Environment,所以会导致配置不生效问题

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值