Flutter应用中通过API实时获取并展示数字货币汇率方案咨询
实时数字货币汇率展示解决方案
每秒发起一次请求的轮询策略并不推荐——这会给API服务器带来不必要的压力,大概率触发限流机制,同时也会浪费前端的网络资源和性能。下面是更合理的几种实现方案:
方案1:服务器推送事件(SSE)
这是适配「变化时即刻更新」需求的最优方案之一,由服务器主动向客户端推送汇率变化,无需前端频繁请求。
- 前端实现示例:
// 建立SSE连接 const eventSource = new EventSource('/api/real-time-rates'); // 接收服务器推送的更新 eventSource.onmessage = function(event) { const latestRate = JSON.parse(event.data); // 更新页面显示逻辑 document.getElementById('rate-panel').textContent = `${latestRate.pair}: ${latestRate.price}`; }; // 处理连接错误 eventSource.onerror = function(error) { console.error('SSE连接异常:', error); eventSource.close(); };
- 注意:需要你的API支持SSE协议;如果现有API不支持,可以在后端搭建一层中转服务,定时拉取原API数据,仅当汇率变化时通过SSE推送给前端。
方案2:优化轮询策略(兼容现有API)
如果必须基于轮询实现,一定要做以下优化:
- 缓存本地最新汇率,每次请求后对比数据,只有当汇率确实变化时才更新页面
- 延长请求间隔(比如5-10秒一次,根据API的实际更新频率调整)
- 增加失败重连的指数退避逻辑(请求失败后逐步延长间隔,恢复后调回正常频率)
- 前端实现示例:
let lastRecordedRate = null; const fetchAndUpdateRate = async () => { try { const res = await fetch('/api/currency-rate'); const currentRate = await res.json(); // 仅当数据变化时更新页面 if (currentRate.price !== lastRecordedRate?.price) { document.getElementById('rate-panel').textContent = `${currentRate.pair}: ${currentRate.price}`; lastRecordedRate = currentRate; } } catch (err) { console.error('汇率请求失败:', err); } finally { // 5秒后发起下一次请求 setTimeout(fetchAndUpdateRate, 5000); } }; // 初始化请求 fetchAndUpdateRate();
方案3:WebSocket双向连接
适合实时性要求极高、需要双向交互的场景(比如订阅特定货币对),建立连接后服务器可主动推送变化,前端也能随时发送指令。
- 前端实现示例:
const ws = new WebSocket('ws://your-server/ws/rates'); ws.onopen = () => { console.log('WebSocket连接已建立'); // 可发送订阅指令,比如订阅BTC/USDT ws.send(JSON.stringify({ action: 'subscribe', pair: 'BTC-USDT' })); }; ws.onmessage = (event) => { const latestRate = JSON.parse(event.data); document.getElementById('rate-panel').textContent = `${latestRate.pair}: ${latestRate.price}`; }; ws.onerror = (err) => { console.error('WebSocket异常:', err); }; ws.onclose = () => { console.log('连接断开,尝试重连'); setTimeout(() => initWebSocket(), 3000); }; // 封装重连逻辑 function initWebSocket() { // 重复上述WebSocket初始化代码 }
内容的提问来源于stack exchange,提问作者user15723984
相关产品推荐
相关产品推荐

