Gateway—网关服务

本文介绍了Spring Cloud Gateway作为服务网关的功能,包括路由、Predicate断言(Path、Query、Header、Host)和过滤器(内置过滤器、自定义过滤器、全局过滤器)。同时,讲解了动态路由配置与使用Eureka实现服务发现,以及网关的限流策略和令牌桶算法的应用。
摘要由CSDN通过智能技术生成

⼀、网关介绍

使用服务网关作为接口服务的统⼀代理,前端通过网关完成服务的统⼀调用

在这里插入图片描述

  • 网关可以干什么?
    路由:接口服务的统⼀代理,实现前端对接⼝服务的统⼀访问
    过滤:对用户请求进行拦截、过滤(用户鉴权)、监控
    限流:限制用户的访问流量
  • 常用的网关
    Nginx
    Spring Cloud Netflix zuul
    Spring Cloud Gateway

Nginx通常被用作应用服务器网关(Tomcat集群,Redis集群,前端浏览器网关),
zuul或者gateway通常被用作服务网关(springcloud微服务)

二、Gateway使用

Route: 路由是网关的基本组成部分,它是由id、目标uri、断⾔组成,如果断⾔为true,则匹配该路由,转向到当前路由的URI
Predicate:断⾔,用户请求的匹配规则
Filter:过滤器,用于对请求进行前置、后置处理(可以在网关实现对请求或相应的加工处理)

在这里插入图片描述

  • 添加依赖
<dependency>
	<groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
  • 添加配置
server:
 port: 9999
spring:
 application:
 	name: gateway-server
 cloud:
 	gateway:
 		routes:
		 # 配置api-service1路由规则
		 # id随便起
		 - id: api-service1
		 uri: http://localhost:8001
		 # 断言规则:路径里有product的跳转
		 # http://localhost:9999/product/query  —>  http://localhost:8001/product/query
		 predicates:
		 	- Path=/product/**
		 
		 # 配置api-service2路由规则
		 - id: api-service2
		 uri: http://localhost:8002
		 predicates:
		 -	 Path=/order/**

三、Predicate断言

SpringCloud Gateway提供了多种断⾔匹配的⽅式:
After
Before
Between
Cookie
Header
Host
Method
Path
Query
RemoteAddr
Weight

3.1 Path

根据请求路径的正则匹配

server:
 port: 9999
spring:
 application:
 	name: gateway-server
 cloud:
 	gateway:
 		routes:
		 # 配置api-service1路由规则
		 # id随便起
		 - id: api-service1
		 uri: http://localhost:8001
		 # 断言规则:路径里有product的跳转
		 # http://localhost:9999/product/query  —>  http://localhost:8001/product/query
		 predicates:
		 	- Path=/product/**
		 
		 # 配置api-service2路由规则
		 - id: api-service2
		 uri: http://localhost:8002
		 predicates:
		 	- Path=/order/**

3.2 Query

根据请求携带的参数匹配路由

spring:
 application:
	 name: gateway-server
 cloud:
	 gateway:
	 	routes:
 			- id: aaa
			 uri: http://localhost:8001
			 predicates:
			 # http://localhost:9999/product/query?name=wang ---> http://localhost:8001/product/query?name=wang
			 	- Query=name
			 
			 - id: bbb
			 uri: http://localhost:8002
			 predicates:
			 #如果请求url中带有pwd参数 ---> http://localhost:8002
			 	- Query=pwd

3.3 Header

根据Header中携带的参数匹配

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值