在 asp.net 网络应用程序中使用静态字典
Use static dictionary in asp.net web application
我在 asp.net 网络应用程序中使用 SignalR。 SignalR hub 中不存在会话状态,因此我决定将 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);
}
}
根据特定的控制器请求,我想使用 signalR 将数据发送到客户端。知道当前用户的用户名,我可以很容易地为客户端获取connectionId并发送数据。
我在控制器中使用 Get
方法。
我在 hub 的 OnConnected()
和 OnDisconnected()
方法中分别使用了 Add
和 Remove
方法。
我感兴趣的是,此解决方案是否会在我的 Web 应用程序中出现有关线程安全(或其他)的任何问题?什么是更好的方法?
如果您使用静态字典,您将无法 scale out 您的 API。
每个实例都会保留一个不同的静态字典,因此通知不会总是到达目的地,请考虑 azure signalr 或某种持久性存储,如 redis。
你能做的最好,这就是 Microsoft 文档中所说的,将用户映射到组,即使它会生成具有单个用户的组或具有实际上是同一用户的许多用户的组。即使您将使用 Redis backplane
或 Azure SignalR
,您也会在所有上下文中拥有这些组,并且可以与他们交流、添加、删除等等...
A single user can have multiple connections to a SignalR app. For example, a user could be connected on their desktop as well as their phone. Each device has a separate SignalR connection, but they're all associated with the same user. If a message is sent to the user, all of the connections associated with that user receive the message.
我在 asp.net 网络应用程序中使用 SignalR。 SignalR hub 中不存在会话状态,因此我决定将 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);
}
}
根据特定的控制器请求,我想使用 signalR 将数据发送到客户端。知道当前用户的用户名,我可以很容易地为客户端获取connectionId并发送数据。
我在控制器中使用 Get
方法。
我在 hub 的 OnConnected()
和 OnDisconnected()
方法中分别使用了 Add
和 Remove
方法。
我感兴趣的是,此解决方案是否会在我的 Web 应用程序中出现有关线程安全(或其他)的任何问题?什么是更好的方法?
如果您使用静态字典,您将无法 scale out 您的 API。 每个实例都会保留一个不同的静态字典,因此通知不会总是到达目的地,请考虑 azure signalr 或某种持久性存储,如 redis。
你能做的最好,这就是 Microsoft 文档中所说的,将用户映射到组,即使它会生成具有单个用户的组或具有实际上是同一用户的许多用户的组。即使您将使用 Redis backplane
或 Azure SignalR
,您也会在所有上下文中拥有这些组,并且可以与他们交流、添加、删除等等...
A single user can have multiple connections to a SignalR app. For example, a user could be connected on their desktop as well as their phone. Each device has a separate SignalR connection, but they're all associated with the same user. If a message is sent to the user, all of the connections associated with that user receive the message.