Spring Cloud 学习笔记(5) 网关 spring-cloud-gateway

1. 背景

spring-cloud-gateway 是替代 zuul 的一个网关实现,本节我们学习它。

2.知识

spring-cloud-gateway 提供了一个建立在Spring生态系统之上的API网关,旨在提供一种简单而有效的方法路由到api,并为它们提供横切关注点,如:安全性、监控/指标和弹性等。

特性:

  • 动态路由
  • 路由匹配方式 支持 在Spring内置的处理程序映射
  • HTTP请求的路由匹配(路径、方法、报头、主机等)
  • 支持匹配路由的过滤器

过滤器是个很重要的组件,它可以修改下游HTTP请求和HTTP响应(添加/删除报头,添加/删除参数,重写路径,设置路径,Hystrix等…)

3. 示例

1、添加依赖

dependencies {
    implementation 'org.springframework.cloud:spring-cloud-starter-gateway'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
    implementation 'org.springframework.cloud:spring-cloud-starter-netflix-eureka-client'
    implementation 'org.springframework.boot:spring-boot-starter-actuator'
    compileOnly group: 'org.projectlombok', name: 'lombok', version: '1.18.20'
    implementation group: 'com.google.code.gson', name: 'gson', version: '2.8.6'


}

配置文件

server:
  port: 9000

spring:
  application:
    name: api-gateway

  cloud:
    gateway:
      discovery:
        locator:
          enabled: true
          lower-case-service-id: true
      globalcors:
        corsConfigurations:
          '[/auth/**]':
            allowedOrigins: '*'
            allowedHeaders:
              - x-auth-token
              - x-request-id
              - Content-Type
              - x-requested-with
              - x-request-id
            allowedMethods:
              - GET
              - POST
              - OPTIONS
      routes:
        - id: auth-service
          uri: lb://auth-service
          predicates:
            - Path=/auth/**
          filters:
            - StripPrefix=1
        - id: hello-service-1
          uri: lb://hello-service-1
          predicates:
            - Path=/hello/**
          filters:
            - StripPrefix=1

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:1111/eureka/
  instance:
    prefer-ip-address: true

# 配置Gateway日志等级,输出转发细节信息
logging:
  level:
    org.springframework.cloud.gateway: debug

说明
这里配置了Eureka的客户端,将自己注册到Eureka,并从Eureka获得服务列表。

路由的配置
在 router 部分 有这个配置

id: auth-service
          uri: lb://auth-service
          predicates:
            - Path=/auth/**
          filters:
            - StripPrefix=1

它描述了,来自 /auth/** 的地址,路由到 lb://auth-service 服务。我这里结合了 Eureka 使用,将会将请发发送到 在Eureka 里注册过的的名字叫做“auth-service”的服务实例。

StripPrefix=1 说明了要在 路由过程中处理掉第一个路径节点后再讲网址转发到具体的某个实例服务中。

filters:
            - StripPrefix=1

4. 扩展

我的Demo示例:https://github.com/vir56k/demo/tree/master/springboot/gateway_demo

5.参考:

《Spring Cloud微服务实战》https://spring.io/projects/spring-cloud-gatewayhttps://github.com/spring-cloud/spring-cloud-gatewayhttps://spring.io/guides/gs/gateway/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值