导读:在SpringCloud体系架构中,咱们须要部署一个单独的网关服务对外提供访问入口,而后网关服务根据配置好的规则将请求转发至具体的后端服务,本章内容主要是给咱们的微服务加上网关SpringCloud Gateway。html
咱们有了三个服务account-service
,product-service
,order-service
。如今有客户端WEB应用
或APP应用
须要访问后端服务获取数据那么就须要在客户端维护好三个服务的访问路径。java
这样的架构会有以下几个典型的问题:spring
因此咱们须要在微服务以前加一个网关服务,让全部的客户端只要访问网关,网关负责对请求进行转发;将权限校验逻辑放到网关的过滤器中,后端服务不须要再关注权限校验的代码;只须要对外提供一个可供外网访问的域名地址,新增服务后也不须要再让运维人员进行网络配置了,这样上面的架构就变成了以下所示:apache
在项目中创建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
微服务的/**
架构
好了,各位朋友们,本期的内容到此就所有结束啦,能看到这里的同窗都是优秀的同窗,下一个升职加薪的就是你了!若是以为这篇文章对你有所帮助的话请扫描下面二维码加个关注。"转发" 加 "在看",养成好习惯!我们下期再见!app
系列文章负载均衡
欢迎扫码关注微信公众号或 我的博客