Back結構是指在前端與後端之間設置一個中間層,在前端頁面調用後端服務時,先將請求發送給Back端,Back端再將請求發送給後端服務並將響應返回給前端。
一、為什麼需要Back結構
1、降低前後端耦合度
在傳統的前後端分離架構中,前端和後端通信需要按照約定的接口進行交互。當接口發生變化時,前後端都需要進行相應的修改,影響到整個系統的穩定性和開發進度。而Back結構則將雙方之間的接口進行了封裝,前端只需要調用中間層的接口即可,後端的修改對前端的影響大大降低。
2、提高前端性能
在Back結構中,Back端會將多個請求合併成一個請求,減少了前端與後端的通信流量,提高了前端性能。
3、保護後端安全
通過Back結構,後端不需要將API接口暴露在公網中,只需要將API暴露給Back端,可以保護後端的API安全。
二、Back結構的實現方式
1、使用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結構的優缺點
1、優點
(1)降低前後端耦合度,增加系統的可維護性和可擴展性;
(2)提高前端性能,將多個請求合併成一個請求,減少了通信流量;
(3)保護後端安全,後端API接口不需要暴露在公網中。
2、缺點
(1)引入中間層增加了系統的複雜度;
(2)增加了系統響應時間;
(3)需要額外的開發成本和維護成本。
原創文章,作者:NGDF,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/135552.html