前端处理API接口故障:多接口自动切换的实现方案

因为在开发APP,一个接口如果不通(被挂了)又不能改了重新打包让用户再下载软件更新,所以避免这种情况,跟后端讨论多备用接口地址自动切换的方案,自动切换到备用的接口地址,并保证后续所有的请求都使用当前可用的接口地址,以供参考(非必要可以不使用)

其实这种会出现很多问题,当不同的用户访问的服务器地址不一样,而每个服务器的数据又不完全同步。所以后端方案是数据库统一,负载均衡。

解决方案思路:
  1. 接口地址列表:维护一个接口地址列表,当请求失败时,依次尝试备用地址。
  2. 全局可用接口地址:一旦找到一个可用的接口地址,所有后续请求都会使用该地址,直到它不可用时再进行切换。
  3. 持久化存储:使用本地存储将当前可用的接口地址存储起来,避免页面刷新后重新从第一个接口地址开始尝试
// 维护当前可用的接口地址,使用本地存储持久化
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);
    });
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值