sae网站开发,合肥市做外贸网站的公司,海外网站开发,网络管理系统页面因为在开发APP#xff0c;一个接口如果不通#xff08;被挂了#xff09;又不能改了重新打包让用户再下载软件更新#xff0c;所以避免这种情况#xff0c;跟后端讨论多备用接口地址自动切换的方案#xff0c;自动切换到备用的接口地址#xff0c;并保证后续所有的请求都…因为在开发APP一个接口如果不通被挂了又不能改了重新打包让用户再下载软件更新所以避免这种情况跟后端讨论多备用接口地址自动切换的方案自动切换到备用的接口地址并保证后续所有的请求都使用当前可用的接口地址以供参考非必要可以不使用。
其实这种会出现很多问题当不同的用户访问的服务器地址不一样而每个服务器的数据又不完全同步。所以后端方案是数据库统一负载均衡。
解决方案思路
接口地址列表维护一个接口地址列表当请求失败时依次尝试备用地址。全局可用接口地址一旦找到一个可用的接口地址所有后续请求都会使用该地址直到它不可用时再进行切换。持久化存储使用本地存储将当前可用的接口地址存储起来避免页面刷新后重新从第一个接口地址开始尝试
// 维护当前可用的接口地址使用本地存储持久化
let currentInterfaceUrl uni.getStorageSync(currentInterfaceUrl) || http://192.168.0.165:8889/platform-api/app/;
const interfaceUrls [http://192.168.0.165:8889/platform-api/app/, http://192.168.0.166:8889/platform-api/app/, http://192.168.0.167:8889/platform-api/app/
];// 通用的请求方法
function request(url, postData {}, method GET, contentType application/json) {return new Promise((resolve, reject) {function tryRequest(attempt) {if (attempt interfaceUrls.length) {reject(所有接口地址均不可用);return;}let currentUrl interfaceUrls[attempt];uni.request({url: currentUrl url,data: postData,header: {content-type: contentType,token: uni.getStorageSync(token) // 获取token},method: method,success: (res) {if (res.statusCode 200) {// 更新全局接口地址if (currentInterfaceUrl ! currentUrl) {currentInterfaceUrl currentUrl;uni.setStorageSync(currentInterfaceUrl, currentInterfaceUrl);}resolve(res.data);} else {reject(res.data.msg);}},fail: () {console.log(当前接口地址不可用尝试下一个地址...);tryRequest(attempt 1); // 尝试下一个接口地址}});}// 从当前可用的接口地址开始请求let attempt interfaceUrls.indexOf(currentInterfaceUrl);tryRequest(attempt);});
}