系列文章目录
1. 项目介绍及环境配置
2. 短信验证码登录
3. 用户信息
4. MongoDB
5. 推荐好友列表/MongoDB集群/动态发布与查看
6. 圈子动态/圈子互动
7. 即时通讯(基于第三方API)
8. 附近的人(百度地图APi)
9. 小视频
10.网关配置
文章目录
- 系列文章目录
- 一、 问题分析
- 二、 搭建网关工程
- 1. 创建工程
- 2. 导入依赖
- 3. 配置引导类
- 4. 添加配置文件
- 5. 跨域支持
- 6. 测试
- 三、 统一鉴权
- 1. 添加配置文件
- 2. 自定义过滤器
- 3. Postman
- 四. 配置中心
- 1. 添加bootstrap.yml配置
- 2. 所有 bootstrap 配置
一、 问题分析
针对客户端API层,需要配置集群保证高可用,使用API网关解决以下问题:
- 客户端直接访问应用集群
- 访问集群需要兼顾负载均衡和容错
- 多WEB层进行路由转发,统一的拦截过滤处理
API网关 有很多实现方式,我们通过SpringCloud Gateway实现,使用Nacos作为配置中心
二、 搭建网关工程
1. 创建工程
根目录新建 tanhua-gateway
文件:
2. 导入依赖
新建 tanhua-gateway/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>tanhua</artifactId>
<groupId>com.itheima</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>tanhua-gateway</artifactId>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!-- 监控检查-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!-- nacos配置中心依赖支持 -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
<dependency>
<groupId>com.itheima</groupId>
<artifactId>tanhua-commons</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
</project>
3. 配置引导类
新建 tanhua-gateway/src/main/java/com/tanhua/gateway/GatewayApplication.java
文件:
@SpringBootApplication
public class GatewayApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayApplication.class, args);
}
}
4. 添加配置文件
新建 tanhua-gateway/src/main/resources/application.yml
文件:
server:
port: 8888
spring:
profiles:
active: prod
application:
name: tanhua-gateway
cloud:
# 配置注册中心
nacos:
discovery:
server-addr: 192.168.136.160:8848
gateway:
globalcors:
add-to-simple-url-handler-mapping: true
corsConfigurations:
'[/**]':
allowedHeaders: "*"
allowedOrigins: "*"
allowedMethods:
- GET
- POST
- DELETE
- PUT
- OPTION
# 配置路由
routes:
# 探花系统
- id: tanhua-app-server
uri: lb://tanhua-app-server
predicates:
- Path=/app/**
filters:
- StripPrefix= 1
# 后台系统
- id: tanhua-admin
uri: lb://tanhua-admin
predicates:
- Path=/admin/**
filters:
- StripPrefix= 1
5. 跨域支持
新建 tanhua-gateway/src/main/java/com/tanhua/gateway/config/CorsConfig.java
文件:
/**
* 跨域支持
*/
@Configuration
public class CorsConfig {
@Bean
public CorsWebFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration();
config.addAllowedMethod("*");
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
UrlBasedCorsConfigurationSource source =
new UrlBasedCorsConfigurationSource(new PathPatternParser());
source.registerCorsConfiguration("/**", config);
return new CorsWebFilter(source);
}
}
6. 测试
三、 统一鉴权
1. 添加配置文件
编辑 tanhua-gateway/src/main/resources/application.yml
文件:
server:
port: 8888
spring:
profiles:
active: prod
application:
name: tanhua-gateway
cloud:
# 配置注册中心
nacos:
discovery:
server-addr: 192.168.136.160:8848
gateway:
globalcors:
add-to-simple-url-handler-mapping: true
corsConfigurations:
'[/**]':
allowedHeaders: "*"
allowedOrigins: "*"
allowedMethods:
- GET
- POST
- DELETE
- PUT
- OPTION
# 配置路由
routes:
# 探花系统
- id: tanhua-app-server
uri: lb://tanhua-app-server
predicates:
- Path=/app/**
filters:
- StripPrefix= 1
# 后台系统
- id: tanhua-admin
uri: lb://tanhua-admin
predicates:
- Path=/admin/**
filters:
- StripPrefix= 1
gateway:
excludedUrls: /user/login,/user/loginVerification,/system/users/verification,/system/users/login
2. 自定义过滤器
新建 tanhua-gateway/src/main/java/com/tanhua/gateway/filters/AuthFilter.java
文件:
@Component
public class AuthFilter implements GlobalFilter, Ordered {
@Value("${gateway.excludedUrls}")
private List<String> excludedUrls; //需要配置不校验的连接
//过滤器核心业务代码
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//1、排除不需要权限检验的连接
String path = exchange.getRequest().getURI().getPath(); //当前请求连接
if(excludedUrls.contains(path)) {
return chain.filter(exchange);
}
//2、获取token并校验 (xxxxxx , Bearer xxxxx)
String token = exchange.getRequest().getHeaders().getFirst("Authorization");
if(!StringUtils.isEmpty(token)) {
token = token.replaceAll("Bearer ","");
}
boolean verifyToken = JwtUtils.verifyToken(token);
//3、如果检验失败,相应错误状态:401
if(!verifyToken) {
Map<String, Object> responseData = new HashMap<>();
responseData.put("errCode", 401);
responseData.put("errMessage", "用户未登录");
return responseError(exchange.getResponse(),responseData);
}
return chain.filter(exchange);
}
//响应错误数据
private Mono<Void> responseError(ServerHttpResponse response, Map<String, Object> responseData){
// 将信息转换为 JSON
ObjectMapper objectMapper = new ObjectMapper();
byte[] data = new byte[0];
try {
data = objectMapper.writeValueAsBytes(responseData);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
// 输出错误信息到页面
DataBuffer buffer = response.bufferFactory().wrap(data);
response.setStatusCode(HttpStatus.UNAUTHORIZED);
response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
return response.writeWith(Mono.just(buffer));
}
//配置执行顺序
public int getOrder() {
return Ordered.LOWEST_PRECEDENCE;
}
}
3. Postman
四. 配置中心
Nacos提供了注册中心和配置管理的能力,使用Nacos可以快速实现服务发现、服务配置管理等需求
1. 添加bootstrap.yml配置
!!! 删除 application.yml
文件
新建 tanhua-gateway/src/main/resources/bootstrap.yml
文件:
spring:
profiles:
# active: prod
active: dev
application:
name: tanhua-gateway
cloud:
nacos:
discovery:
server-addr: 192.168.136.160:8848
config:
server-addr: 192.168.136.160:8848
file-extension: yml
2. 所有 bootstrap 配置
Gitee仓库地址(所有 bootstrap 配置): https://gitee.com/yuan0_0/tanhua_bootstrap.git