赞
踩
在微服务架构中一个系统会被拆分成多个微服务。那么作为客户端(前端)要如何去调用这么多的微服务?如果没有网关的存在,我们只能在客户端记录每个微服务的地址,然后分别去用。
这样的架构,会存在诸多的问题:
每个业务都会需要鉴权、限流、权限校验、跨域等逻辑,如果每个业务都各自为站。自己造轮子实现一遍,完全没必要,完全可以抽离出来,放到一个统一的地方去做
。
网关:所谓API网关,就是指系统的同一入口,它封装了应用程序的内部结构,为客户端提供统一服务,一些与业务功能本身无关的公共逻辑可以在这里实现,诸如认证、鉴权、监控、路由转发等待
添加上API网关之后,系统变成三层结构,系统的架构图如下:
加入网关之后的架构图
- 路由
路由是网关中最基础的部分,路由信息包括一个ID、一个目的URL、一组断言工厂、一组filter组成。如果断言为真,则说明请求的RUL和配置的路由匹配;- 断言
Java8中的断言函数,gateway中的断言函数类型是spring5.0框架中的servletWebExchange,断言函数允许开发者去定义匹配http request中的任何信息,比如请求头和参数等。- 过滤器
gateway中的filter分为Gateway Filter和Global Filter,filter可以对请求和响应处理
添加依赖
<!--添加springcloud gateway依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
server: port: 8090 # gateway配置 spring: application: name: api-gateway cloud: #gateway配置 gateway: #路由规则 routes: - id: order_router #路由的唯一标识,路由到order uri: http://localhost:8081 #需要转发的地址 #断言规则 用于路由规则的匹配 predicates: - Path=/order-server/** # http://localhost:8090/order-server/order/buyProduct 路由到↓ # http://localhost:8081/order-server/order/buyProduct filters: - StripPrefix=1 #内置过滤器,转发之前去掉第一层路径 # http://localhost:8081/order-server/order/buyProduct 去掉后 ↓ # http://localhost:8081/order/buyProduct
你这个是springcloud gateway吧,我跟你说一下为什么这么写配置,是这样的,lb代表了负载均衡,有这个标志后,gateway就知道需要进行负载均衡,转发到lb://后面跟的服务名对应的某台服务器上,至于如何实现负载均衡,是通过负载均衡组件来的,比如ribbon或者springcloud-loadbalancer组件拿到服务列表,从而进行服务的转发。所以lb://,其实跟服务注册中心没有关系,就算不是nacos,用其它的,比如eureka,也是这么写lb://。
server: port: 8090 # gateway配置 spring: application: name: api-gateway cloud: #nacos配置 nacos: discovery: server-addr: 192.168.184.15:8848 username: nacos password: nacos #gateway配置 gateway: #路由规则 routes: - id: order_router #路由的唯一标识,路由到order uri: lb://order-service #需要转发的地址 lb:使用nacos中的本地负载均衡策略 #断言规则 用于路由规则的匹配 predicates: - Path=/order-server/** # http://localhost:8090/order-server/order/buyProduct 路由到↓ # http://localhost:8081/order-server/order/buyProduct filters: - StripPrefix=1 #内置过滤器,转发之前去掉第一层路径 # http://localhost:8081/order-server/order/buyProduct 去掉后 ↓ # http://localhost:8081/order/buyProduct
当服务注册到nacos后,断言规则可以用服务名来进行匹配,此时配置可以进行简化(约定服务名和断言规则都从nacos获取)
server: port: 8090 # gateway配置 spring: application: name: api-gateway cloud: #nacos配置 nacos: discovery: server-addr: 192.168.184.15:8848 username: nacos password: nacos #gateway配置 gateway: discovery: locator: enabled: true #是否启动自动识别nacos服务(约定大于配置)
此时访问:http://localhost:8090/order-service/order/buyProduct
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。