导读:在SpringCloud体系架构中,我们需要部署一个单独的网关服务对外提供访问入口,然后网关服务根据配置好的规则将请求转发至具体的后端服务,本章内容主要是给我们的微服务加上网关SpringCloud Gateway。
我们有了三个服务 account-service , product-service , order-service 。现在有客户端 WEB应用 或 APP应用 需要访问后端服务获取数据那么就需要在客户端维护好三个服务的访问路径。
这样的架构会有如下几个典型的问题:
所以我们需要在微服务之前加一个网关服务,让所有的客户端只要访问网关,网关负责对请求进行转发;将权限校验逻辑放到网关的过滤器中,后端服务不需要再关注权限校验的代码;只需要对外提供一个可供外网访问的域名地址,新增服务后也不需要再让运维人员进行网络配置了,这样上面的架构就变成了如下所示:
在项目中建立cloud-gateway模块, spring-cloud-gateway 作为微服务体系中的一环也需要将自身注册进Nacos并集成Nacos配置中心。
pom.xml <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>cloud-aliaba</artifactId>
<groupId>com.jianzh5.cloud</groupId>
<version>1.0.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>cloud-gateway</artifactId>
<dependencies>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
</dependencies>
</project>
@SpringBootApplication
@EnableDiscoveryClient
public class GateWayApplication {
public static void main(String[] args) {
SpringApplication.run(GateWayApplication.class, args);
}
}
spring:
application:
name: cloud-gateway
cloud:
nacos:
config:
server-addr: 10.0.10.48:8848
file-extension: yml
namespace: 7e8ccc22-6f51-42fa-bcf1-db45f99dbf57
server:
port: 8090
spring:
cloud:
nacos:
discovery:
server-addr: 10.0.10.48:8848
gateway:
discovery:
locator:
enabled: true
routes:
- id: product-service
uri: lb://product-service
predicates:
- Path=/product/**
- id: account-service
uri: lb://account-service
predicates:
- Path=/account/**
- id: order-service
uri: lb://order-service
predicates:
- Path=/order/**
配置详解:
id: 在所有路由定义中需要唯一,不能重复
uri: lb:// lb://为固定写法,表示开启负载均衡; 即服务在Nacos中注册的名字
predicates:- Path=/product/ 使用"Path Route Predicate Factory",规则为/product/ 的请求都还转发至微服务product-service中。
上面的配置逻辑为:
① 以 http://localhost:8090/product/** 的访问路径会转发到 product-service 微服务的 /**
② 以 http://localhost:8090/account/** 的访问路径会转发到 account-service 微服务的 /**
③ 以 http://localhost:8090/order/** 的访问路径会转发到 order-service 微服务的 /**
好了,各位朋友们,本期的内容到此就全部结束啦,能看到这里的同学都是优秀的同学,下一个升职加薪的就是你了!
如果觉得这篇文章对你有所帮助的话请扫描下面二维码加个关注。
"转发" 加 "在看",养成好习惯!咱们下期再见!