You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

投注网站:仅MySQL表新增行时刷新网页指定区域的技术方案咨询

解决实时投注更新的低负载方案:替代AJAX轮询

Hey there! I get it—running a betting site where you need to update all active users' pages when a new bet comes in, but constant 1-second AJAX polls are tanking your server. Let's ditch that inefficient approach and go for smarter, lower-load alternatives. Here are your top options:

1. WebSocket:双向实时通信的首选

WebSocket creates a persistent, full-duplex connection between the client and server, so the server can push updates to clients the second a new bet is inserted—no repeated polling needed.

How to implement it:

  • Frontend setup: Use the native WebSocket API to connect to your server. When a new message is received, trigger a refresh of your target page section (e.g., fetch the latest bets and replace the DOM element).
    const ws = new WebSocket('ws://your-server-url/bets');
    ws.onmessage = function(event) {
      // Refresh the bets section
      const betsSection = document.getElementById('live-bets');
      // 可以选择直接接收更新后的HTML,或者用新ID拉取单条投注数据
      betsSection.innerHTML = event.data; 
    };
    
  • Backend & MySQL integration:
    • Option 1: Use MySQL triggers to push a notification to a message broker (like Redis Pub/Sub) whenever a new row is inserted into your bets table. Your WebSocket server subscribes to this broker and broadcasts the update to all connected clients.
      Example MySQL trigger (simplified):
      DELIMITER //
      CREATE TRIGGER new_bet_trigger AFTER INSERT ON bets
      FOR EACH ROW
      BEGIN
        // 通过自定义函数或外部脚本将消息推送到Redis
        CALL redis_publish('new_bet_channel', NEW.id);
      END //
      DELIMITER ;
      
    • Option 2: Monitor MySQL's binary log (binlog) to detect insert events. Tools like Maxwell or Debezium can stream binlog changes to your WebSocket server, which then pushes updates to clients.

Pros:

  • 近乎实时的更新速度
  • 服务器负载极低(无需重复HTTP请求)
  • 支持双向通信(后续可扩展客户端专属更新功能)

Cons:

  • 需要部署独立的WebSocket服务器(可与现有后端集成)
  • 需处理客户端重连逻辑(临时断连后自动恢复)

2. Server-Sent Events (SSE):单向推送的轻量选择

如果不需要双向通信(仅需服务器向客户端推送更新),SSE是比WebSocket更简单的替代方案。它基于持久HTTP连接,服务器可随时向客户端发送事件。

How to implement it:

  • Frontend setup: Use the EventSource API监听服务器发送的事件。
    const eventSource = new EventSource('/api/live-bets');
    eventSource.onmessage = function(event) {
      // 更新目标区域
      document.getElementById('live-bets').innerHTML = event.data;
    };
    // 监听连接错误
    eventSource.onerror = function() {
      console.error('SSE connection failed, reconnecting...');
      setTimeout(() => window.location.reload(), 5000);
    };
    
  • Backend setup: 创建一个保持HTTP连接的端点,当有新投注插入时发送事件。可结合WebSocket方案中的MySQL触发器/binlog监听逻辑来触发事件推送。

Pros:

  • 比WebSocket实现更简单(基于标准HTTP,无需特殊服务器配置)
  • EventSource内置自动重连机制
  • 单向更新场景下的开销比WebSocket更低

Cons:

  • 仅支持服务器到客户端的单向通信
  • 部分老旧浏览器支持有限(现代主流浏览器均已支持)

3. Long Polling:兼容旧环境的折中方案

长轮询是普通AJAX轮询的升级版本:客户端发送请求后,服务器会持有请求直到有新数据或超时,返回响应后客户端立即发起下一次请求。

How to implement it:

  • Frontend:
    function longPoll() {
      fetch('/api/new-bets')
        .then(response => response.text())
        .then(data => {
          if (data) {
            // 更新投注区域
            document.getElementById('live-bets').innerHTML = data;
          }
          // 立即发起下一次请求
          longPoll();
        })
        .catch(error => {
          // 出错后延迟重试
          setTimeout(longPoll, 5000);
        });
    }
    // 页面加载时启动长轮询
    longPoll();
    
  • Backend: /api/new-bets端点会等待新投注插入(通过数据库触发器或内部轮询,但仅在有请求等待时执行)后再返回响应。

Pros:

  • 兼容所有浏览器(无需WebSocket/SSE支持)
  • 请求次数远少于普通轮询(仅在上一次请求完成后发起新请求)

Cons:

  • 延迟略高于WebSocket/SSE
  • 服务器需要持有连接,资源占用比WebSocket高,但远低于普通轮询

额外优化建议

  • 仅更新变化的数据: 不要替换整个区域,只发送新投注的数据并追加到DOM中,减少数据传输和前端渲染开销。
  • 使用消息中间件: Redis Pub/Sub或RabbitMQ可解耦MySQL事件检测与推送服务器,提升系统扩展性和可维护性。
  • 批量更新(若需): 如果投注频率极高,可每2秒批量推送一次新投注,减少前端频繁更新和服务器压力。

内容的提问来源于stack exchange,提问作者karlosuccess

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:50:14