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

.NET Core 6+SignalR多副本Docker Swarm部署无法稳定连接Redis

.NET Core 6 SignalR + Redis 在Docker Swarm多副本下连接不稳定问题

我基于.NET Core 6构建的应用部署在Docker Swarm集群中,多副本分布于不同节点,采用SignalR实现实时通信,Redis用于管理会话数据。单副本运行时Redis连接正常,但扩缩至多副本后,Redis连接变得不稳定且无规律,导致应用行为不一致。已排查网络问题、更换.NET Core版本,问题仍存在。以下是复现问题的示例应用代码:

Program.cs

using WebSocketApp.Hubs;

namespace WebSocketApp
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

            builder.Services.AddSignalR(options =>
               {
                   options.ClientTimeoutInterval = TimeSpan.FromSeconds(30);
               })
               .AddStackExchangeRedis("10.128.116.21:4009,password=1234", options =>
               {
                   options.Configuration.ChannelPrefix = "WebSoketTest";
                   options.Configuration.AbortOnConnectFail = false;
               });
          
            var app = builder.Build();

            // Configure the HTTP request pipeline.
            if (!app.Environment.IsDevelopment())
            {
                app.UseExceptionHandler("/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseWebSockets();

            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapHub<ChatHub>("/chatHub"); // Map SignalR hub
                endpoints.MapFallbackToFile("index.html");
            });

            app.MapGet("/", () => "Hello World!");

            app.Run();
        }
    }
}

ChatHub.cs

namespace WebSocketApp.Hubs
{
    public class ChatHub : Hub
    {
        public async Task SendMessage(string message)
        {
            await Clients.All.SendAsync("ReceiveMessage", message);
        }
    }
}

index.html

<!DOCTYPE html>
<html>
<head>
    <title>WebSocket Chat</title>
</head>
<body>
    <div>
        <input type="text" id="messageInput" />
        <button onclick="sendMessage()">Send</button>
    </div>
    <div id="chatBox"></div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/5.0.0/signalr.js"></script>
    <script>
        const connection = new signalR.HubConnectionBuilder()
            .withUrl("/chatHub")
            .build();

        // Log incoming messages from the server
        connection.on("ReceiveMessage", (message) => {
            console.log("Received message from server:", message);
            const chatBox = document.getElementById("chatBox");
            const messageDiv = document.createElement("div");
            messageDiv.textContent = message;
            chatBox.appendChild(messageDiv);
        });

        async function sendMessage() {
            const messageInput = document.getElementById("messageInput");
            const message = messageInput.value;

            if (message.trim() !== "") {
                // Log outgoing messages to the server
                console.log("Sending message to server:", message);
                await connection.invoke("SendMessage", message);
                messageInput.value = "";
            }
        }

        connection.start()
            .then(() => console.log("WebSocket connection established"))
            .catch(console.error);
    </script>
</body>
</html>

单副本时连接正常,多容器部署则无法正常工作。已排查所有网络可能存在的问题,未发现异常;也测试了不同版本的.NET Core,结果一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 06:35:19