Spring Cloud Gateway简介
SpringCloud Gateway 是 Spring Cloud 的一个全新项目,该项目是基于 Spring 5.0,Spring Boot 2.0 和 Project Reactor 等技术开发的网关,它旨在为微服务架构提供一种简单有效的统一的 API 路由管理方式。
SpringCloud Gateway 作为 Spring Cloud 生态系统中的网关,目标是替代 Zuul,在Spring Cloud 2.0以上版本中,没有对新版本的Zuul 2.0以上最新高性能版本进行集成,仍然还是使用的Zuul 2.0之前的非Reactor模式的老版本。而为了提升网关的性能,SpringCloud Gateway是基于WebFlux框架实现的,而WebFlux框架底层则使用了高性能的Reactor模式通信框架Netty。
Spring Cloud Gateway 的目标,不仅提供统一的路由方式,并且基于 Filter 链的方式提供了网关基本的功能,例如:安全,监控/指标,和限流
下面案例将通过SpringCloud实现前后端分离 前 端 访 问 地 址 约 定
http://locahost:8086/api/bill/**
1、创建前端项目
1.1添加Springweb依赖
1.2编写html,并使用ajax实现异步请求
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Layui</title>
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<link rel="stylesheet" href="/layui/css/layui.css" tppabs="https://www.layui.site/layui/dist/css/layui.css" media="all">
<!-- 注意:如果你直接复制所有代码到本地,上述css路径需要改成你本地的 -->
</head>
<body>
<table class="layui-hide" id="test"></table>
<script src="/layui/layui.js" charset="utf-8"></script>
<!-- 注意:如果你直接复制所有代码到本地,上述 JS 路径需要改成你本地的 -->
<script>
layui.use('table', function(){
var table = layui.table;
table.render({
elem: '#test'
,url: 'http://localhost:9005/api/bill/list-page'
,cellMinWidth: 80 //全局定义常规单元格的最小宽度,layui 2.2.1 新增
,page: true //开启分页
,limits: [10,20,50] //每页条数的选择项,默认:[10,20,30,40,50,60,70,80,90]。
,limit: 10 //每页默认显示的数量
,cols: [[
{field: 'id', title: 'ID', width:80, sort: true, fixed: 'left'}
,{field: 'title', title: '标题', width:177}
,{field: 'billTime', title: '时间', width:177, sort: true}
,{field: 'typeName', title: '类别', width:177, sort: true}
,{field: 'price', title: '金额', width:177}
,{field: 'explain', title: '说明', width: 177}
]]
});
});
</script>
</body>
</html>
1.3配置文件
server:
port: 8086
servlet:
context-path: /
spring:
application:
name: bill_managerweb
thymeleaf:
cache: false
web:
resources:
static-locations: classpath:/templates/,classpath:/static/
2.进行跨域处理对后端接口加上@CrossOrigin
@RestController
@RequestMapping("/bill")
@CrossOrigin
public class BillController {
@Resource
private TypeService typeService;
@Resource
private BillService billService;
3、创建网关服务
2.1添加依赖Spring Cloud Gateway,如图下图所示。
2.2、配置文件
server:
port: 9005
spring:
application:
name: api-gateway
cloud:
gateway:
routes:
- id: bill-manager
uri: http://127.0.0.1:9003
filters:
- StripPrefix=1
predicates:
- Path=/api/bill/**
2.3微服务网关全局过滤器进行跨域处理
spring:
cloud:
gateway:
globalcors:
cors-configurations:
'[/**]':
allowed-origin-patterns: "*" # spring boot2.4配置
# allowed-origins: "*"
allowed-headers: "*"
allow-credentials: true
allowed-methods:
- GET
- POST
- DELETE
- PUT
- OPTION