我在我的 asp.net web 应用程序中使用 SignalR。 SignalR hub 中不存在 session 状态,因此我决定保存 username <-> connectionId在静态字典中配对。
public static class UsernameConnectionsMaps
{
private static Dictionary<string, string> data = new Dictionary<string, string>();
public static void Add(string username, string connectionId)
{
data[username] = connectionId;
}
public static string Get(string username)
{
return data[username];
}
public static void Remove(string username)
{
return data.Remove(username);
}
}
根据特定的 Controller 请求,我想使用 signalR 将数据发送到客户端。知道当前用户的用户名,我可以轻松获取客户端的 connectionId 并发送数据。
我使用 Get我的 Controller 中的方法。 我用 Add和 Remove hub 中的方法 OnConnected()和 OnDisconnected()方法分别。
我感兴趣的是,此解决方案是否会在我的 Web 应用程序中出现有关线程安全(或其他)的任何问题?什么是更好的方法?
请您参考如下方法:
如果你使用静态字典,你将失去 scale out 的能力。你的 API。 每个实例都会保留一个不同的静态字典,因此通知不会总是到达目的地,请考虑 azure signalr或某种持久性存储,如 Redis。
