一、为什么需要Back结构
- 降低前后端耦合度 在传统的前后端分离架构中,前端和后端通信需要按照约定的接口进行交互。当接口发生变化时,前后端都需要进行相应的修改,影响到整个系统的稳定性和开发进度。而Back结构则将双方之间的接口进行了封装,前端只需要调用中间层的接口即可,后端的修改对前端的影响大大降低。
- 提高前端性能 在Back结构中,Back端会将多个请求合并成一个请求,减少了前端与后端的通信流量,提高了前端性能。
- 保护后端安全 通过Back结构,后端不需要将API接口暴露在公网中,只需要将API暴露给Back端,可以保护后端的API安全。
二、Back结构的实现方式
- 使用API Gateway实现Back结构
<?php
//前端向API Gateway发送请求
function sendRequest($url, $data) {
$postData = http_build_query($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
//API Gateway向后端发送请求
function sendBackendRequest($url, $data) {
$postData = http_build_query($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
//使用API Gateway查询订单接口
function queryOrder($orderId) {
$backUrl = 'http://backend.com/queryOrder';
$backData = array('orderId'=>$orderId);
$gatewayUrl = 'http://gateway.com/queryOrder';
$gatewayData = array('backUrl'=>$backUrl, 'backData'=>$backData);
return sendRequest($gatewayUrl, $gatewayData);
}
?>
在这种实现方式中,前端通过向API Gateway发送请求,让API Gateway将请求转发给后端API接口,再将响应返回给前端。 2. 使用服务注册与发现实现Back结构
<?php
//使用Ribbon负载均衡器向后端发送请求
function sendBackendRequest($url, $data) {
$postData = http_build_query($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
//使用服务注册与发现查询订单接口
function queryOrder($orderId) {
$serviceId = 'backend-service';
$instances = getServiceInstances($serviceId);
$instance = chooseInstance($instances);
$url = $instance['url'].'/queryOrder';
$data = array('orderId'=>$orderId);
return sendBackendRequest($url, $data);
}
?>
在这种实现方式中,后端服务会向服务注册中心进行注册,前端通过感知服务注册中心来调用后端服务。
三、Back结构的优缺点
- 优点
- 降低前后端耦合度,增加系统的可维护性和可扩展性;
- 提高前端性能,将多个请求合并成一个请求,减少了通信流量;
- 保护后端安全,后端API接口不需要暴露在公网中。
- 缺点
- 引入中间层增加了系统的复杂度;
- 增加了系统响应时间;
- 需要额外的开发成本和维护成本。