SpringCloud Alibaba系列 Gateway(四)

导读:本篇文章讲解 SpringCloud Alibaba系列 Gateway(四),希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

目录

什么是网关?

网关在微服务中所处的位置

Gateway 的核心概念

路由(Route)

断言(Predicate)

过滤器(Filter)

SpringCloud 整合 Gateway

Gateway 整合 Nacos

自定义全局过滤器


官网:Spring Cloud Gateway

官网文档:https://cloud.spring.io/spring-cloud-gateway/reference/html

所有配置参数文档:https://cloud.spring.io/spring-cloud-gateway/reference/html/appendix.html

什么是网关?

网关系统的唯一对外的入口,介于客户端和服务器端之间的中间层,处理非业务功能,提供路由请求、鉴权、监控、缓存、限流等功能。

网关在微服务中所处的位置

SpringCloud Alibaba系列 Gateway(四)

Gateway 的核心概念

  • 路由(Route)

路由是网关最基础的部分,它由一个 ID,一个目标 URI,一组断言和一组过滤器定义。如果断言为真,则路由匹配。

  • 断言(Predicate)

Java8 中的断言函数。Spring Cloud Gateway 中的断言函数输入类型是 Spring 5.0 框架中 的 ServerWebExchange。Spring Cloud Gateway 中的断言函数允许开发者去定义匹配来自于 Http Request 中的任 何信息,比如请求头和参数等。

  • 过滤器(Filter)

一个标准的 Spring Web Filter。Spring Cloud Gateway 中的 Filter 分为两种类型,分别是 Gateway Filter 和 Global Filter。过滤器将会对请求和响应进行处理。


SpringCloud 整合 Gateway

网关是一个单独的子服务,要新建一个微服务模块

pom.xml 中添加依赖

<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>

pom.xml 中移除依赖

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
</dependency>

application.yml 文件配置 gateway

server:
  port: 7000
spring:
  cloud:
    gateway:
      routes:
        - id: user-service
          uri: http://localhost:9000
          order: 1
          predicates:
            - Path=/user-server/**
          filters:
            - StripPrefix=1

配置说明:

  • routes:核心概念路由。这里配置路由,数组的形式
  • id:自定义路由唯一标识,用于区别于其他的路由
  • uri:路由指向的目的地URL,例如要路由转发到 用户服务,用户服务的地址是 http://localhost:9000,这里就写 http://localhost:9000 
  • order:优先级,数字越小优先级越高
  • predicates:核心概念断言,断言有很多种类型,写多个的时候,必须都满足才转发
    • Path:根据路径断言,意思是通过访问url的前缀匹配到该路由,转发到该路由上的uri地址,这里配置的是/user-server/**。页面访问 http://localhost:7000/user-server/xx,就进入到此路由把 请求转发到 http://localhost:9000/xx 路径上。
    • Header:请求头断言,带有指定请求头的才进行路由,适用场景:公共头
    • Method:请求方法(get、post等)断言,符合的才进行路由
    • Query:请求参数断言,请求包含指定的参数才进行路由,适用场景:公共参数
    • 说明:内置路由是RoutePredicateFactory这个接口的实现。更多断言示例请查看官网:https://docs.spring.io/spring-cloud-gateway/docs/current/reference/html/#gateway-request-predicates-factories
  • filters:核心概念过滤,过滤有很多种,这里使用的是 StripPrefix。

效果:

SpringCloud Alibaba系列 Gateway(四)

SpringCloud Alibaba系列 Gateway(四)


Gateway 整合 Nacos

pom.xml 中添加依赖

<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-loadbalancer</artifactId>
</dependency>

通过 Spring Cloud 原生注解 @EnableDiscoveryClient 开启服务注册发现功能

SpringCloud Alibaba系列 Gateway(四)

application.yml 文件配置 nacos

spring:
  cloud:
    nacos:
      # 配置 nacos 服务地址
      discovery:
        server-addr: 127.0.0.1:8848
    gateway:
      routes:
        - id: user-service
          # 这里就不是写死ip了,这里写注册在nacos上服务名,lb是负载均衡的意思
          uri: lb://user-service
          order: 1
          predicates:
            - Path=/user-server/**
          filters:
            - StripPrefix=1
      # 开启网关自动拉取 nacos 配置的服务
      discovery:
        locator:
          enabled: true

自定义全局过滤器

@Component
public class UserGlobalFilter implements GlobalFilter, Ordered {

	@Override
	public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
		// 这里写业务逻辑, 比如 查询数据库、redis、校验 token 等逻辑
		String token = exchange.getRequest().getHeaders().getFirst("token");
		if (null == token) {
			exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
			// 执行完成,返回 401 失败状态码
			return exchange.getResponse().setComplete();
		}
		// 继续向下一个过滤器执行
		return chain.filter(exchange);
	}

	/**
	 * 设置过滤器的优先级,数字越小,越先执行
	 */
	@Override
	public int getOrder() {
		return 0;
	}
}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/72506.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!