|
| 1 | +--- |
| 2 | +title: Use Azure SignalR Service |
| 3 | +description: Learn how to use Azure SignalR Service in your app server |
| 4 | +author: vicancy |
| 5 | +ms.service: signalr |
| 6 | +ms.topic: how-to |
| 7 | +ms.date: 12/18/2023 |
| 8 | +ms.author: lianwei |
| 9 | +--- |
| 10 | + |
| 11 | +# Use Azure SignalR Service |
| 12 | + |
| 13 | + |
| 14 | +This article shows you how to use SDK in your app server side to connect to SignalR Service when you are using SignalR in your app server. |
| 15 | + |
| 16 | +## Create an Azure SignalR Service instance |
| 17 | + |
| 18 | +Follow [Quickstart: Use an ARM template to deploy Azure SignalR](./signalr-quickstart-azure-signalr-service-arm-template.md) to create a SignalR service instance. |
| 19 | + |
| 20 | +## For ASP.NET Core SignalR |
| 21 | + |
| 22 | +### Install the SDK |
| 23 | + |
| 24 | +Run the command to install SignalR Service SDK to your ASP.NET Core project. |
| 25 | + |
| 26 | +```bash |
| 27 | +dotnet add package Microsoft.Azure.SignalR |
| 28 | +``` |
| 29 | + |
| 30 | +In your `Startup` class, use SignalR Service SDK as the following code snippet. |
| 31 | + |
| 32 | +```csharp |
| 33 | +public void ConfigureServices(IServiceCollection services) |
| 34 | +{ |
| 35 | + services.AddSignalR() |
| 36 | + .AddAzureSignalR(); |
| 37 | +} |
| 38 | + |
| 39 | +public void Configure(IApplicationBuilder app) |
| 40 | +{ |
| 41 | + app.UseEndpoints(routes => |
| 42 | + { |
| 43 | + routes.MapHub<YourHubClass>("/path_for_your_hub"); |
| 44 | + }); |
| 45 | +} |
| 46 | +``` |
| 47 | + |
| 48 | +### Configure connection string |
| 49 | + |
| 50 | +There are two approaches to configure SignalR Service's connection string in your application. |
| 51 | + |
| 52 | +- Set an environment variable with name `Azure:SignalR:ConnectionString` or `Azure__SignalR__ConnectionString`. |
| 53 | + - In Azure App Service, put it in application settings. |
| 54 | +- Pass the connection string as a parameter of `AddAzureSignalR()`. |
| 55 | + |
| 56 | + ```csharp |
| 57 | + services.AddSignalR() |
| 58 | + .AddAzureSignalR("<replace with your connection string>"); |
| 59 | + ``` |
| 60 | + |
| 61 | + or |
| 62 | + |
| 63 | + ```csharp |
| 64 | + services.AddSignalR() |
| 65 | + .AddAzureSignalR(options => options.ConnectionString = "<replace with your connection string>"); |
| 66 | + ``` |
| 67 | + |
| 68 | +### Configure options |
| 69 | + |
| 70 | +There are a few [options](https://github.com/Azure/azure-signalr/blob/dev/src/Microsoft.Azure.SignalR/ServiceOptions.cs) you can customize when using Azure SignalR Service SDK. |
| 71 | +
|
| 72 | +#### `ConnectionString` |
| 73 | + |
| 74 | +- Default value is the `Azure:SignalR:ConnectionString` `connectionString` or `appSetting` in `web.config` file. |
| 75 | +- It can be reconfigured, but make sure the value is **NOT** hard coded. |
| 76 | + |
| 77 | +#### `InitialHubServerConnectionCount` |
| 78 | + |
| 79 | +- Default value is `5`. |
| 80 | +- This option controls the initial count of connections per hub between application server and Azure SignalR Service. Usually keep it as the default value is enough. During runtime, the SDK might start new server connections for performance tuning or load balancing. When you have large number of clients, you can give it a larger number for better throughput. For example, if you have 100,000 clients in total, the connection count can be increased to `10` or `15`. |
| 81 | + |
| 82 | +#### `MaxHubServerConnectionCount` |
| 83 | + |
| 84 | +- Default value is `null`. |
| 85 | +- This option controls the max count of connections allowed per hub between application server and Azure SignalR Service. During runtime, the SDK might start new server connections for performance tuning or load balancing. By default a new server connection starts whenever needed. When the max allowed server connection count is configured, the SDK doesn't start new connections when server connection count reaches the limit. |
| 86 | + |
| 87 | +#### `ApplicationName` |
| 88 | + |
| 89 | +- Default value is `null`. |
| 90 | +- This option can be useful when you want to share the same Azure SignalR instance for different app servers containing the same hub names. If not set, all the connected app servers are considered to be instances of the same application. |
| 91 | + |
| 92 | +#### `ClaimsProvider` |
| 93 | + |
| 94 | +- Default value is `null`. |
| 95 | +- This option controls what claims you want to associate with the client connection. |
| 96 | +It's used when Service SDK generates access token for client in client's negotiate request. |
| 97 | +By default, all claims from `HttpContext.User` of the negotiated request are reserved. |
| 98 | +They can be accessed at [`Hub.Context.User`](/dotnet/api/microsoft.aspnetcore.signalr.hubcallercontext.user). |
| 99 | +- Normally you should leave this option as is. Make sure you understand what happens before customizing it. |
| 100 | + |
| 101 | +#### `AccessTokenLifetime` |
| 102 | + |
| 103 | +- Default value is `1 hour`. |
| 104 | +- This option controls the valid lifetime of the access token, that Service SDK generates for each client. |
| 105 | +The access token is returned in the response to client's negotiate request. |
| 106 | +- When `ServerSentEvent` or `LongPolling` is used as transport, client connection will be closed due to authentication failure after the expired time. |
| 107 | +You can increase this value to avoid client disconnect. |
| 108 | + |
| 109 | +#### `AccessTokenAlgorithm` |
| 110 | + |
| 111 | +- Default value is `HS256` |
| 112 | +- This option provides choice of [`SecurityAlgorithms`](https://github.com/AzureAD/azure-activedirectory-identitymodel-extensions-for-dotnet/blob/dev/src/Microsoft.IdentityModel.Tokens/SecurityAlgorithms.cs) when generate access token. Now supported optional values are `HS256` and `HS512`. Note that `HS512` is more secure but the generated token is comparatively longer than that using `HS256`. |
| 113 | +
|
| 114 | +#### `ServerStickyMode` |
| 115 | + |
| 116 | +- Default value is `Disabled`. |
| 117 | +- This option specifies the mode for **server sticky**. When the client is routed to the server that it first negotiates with, we call it **server sticky**. |
| 118 | +- In distributed scenarios, there can be multiple app servers connected to one Azure SignalR instance. As [internals of client connections](signalr-concept-internals.md#client-connections) explains, client first negotiates with the app server, and then redirects to Azure SignalR to establish the persistent connection. Azure SignalR then finds one app server to serve the client, as [Transport Data between client and server](signalr-concept-internals.md#data-transmission-between-client-and-server) explains. |
| 119 | + - When `Disabled`, the client routes to a random app server. In general, app servers have balanced client connections with this mode. If your scenarios are *broadcast* or *group send*, use this default option is enough. |
| 120 | + - When `Preferred`, Azure SignalR tries to find the app server that the client first negotiates with in a way that no other cost or global routing is needed. This one can be useful when your scenario is sent to connection*. *Send to connection* can have better performance and lower latency when the sender and the receiver are routed to the same app server. |
| 121 | + - When `Required`, Azure SignalR always tries to find the app server that the client first negotiates with. This option can be useful when some client context is fetched from `negotiate` step and stored in memory, and then to be used inside `Hub`s. However, this option might have performance drawbacks because it requires Azure SignalR to take other efforts to find this particular app server globally, and to keep globally routing traffics between client and server. |
| 122 | + |
| 123 | +#### `GracefulShutdown` |
| 124 | + |
| 125 | +##### `GracefulShutdown.Mode` |
| 126 | + |
| 127 | +- Default value is `Off` |
| 128 | +- This option specifies the behavior after the app server receives a **SIGINT** (CTRL + C). |
| 129 | +- When set to `WaitForClientsClose`, instead of stopping the server immediately, we remove it from the Azure SignalR Service to prevent new client connections from being assigned to this server. |
| 130 | +- When set to `MigrateClients`, in addition, we try migrating client connections to another valid server. The migration will be triggered only after a message is delivered. |
| 131 | + - `OnConnected` and `OnDisconnected` are triggered when connections be migrated in/out. |
| 132 | + - `IConnectionMigrationFeature` can help you identify if the connection is migrated in/out. |
| 133 | + - See our [sample codes](https://github.com/Azure/azure-signalr/blob/dev/samples/ChatSample) for detail usage. |
| 134 | +
|
| 135 | +##### `GracefulShutdown.Timeout` |
| 136 | + |
| 137 | +- Default value is `30 seconds` |
| 138 | +- This option specifies the longest time in waiting for clients to be closed/migrated. |
| 139 | + |
| 140 | +#### `ServiceScaleTimeout` |
| 141 | + |
| 142 | +- Default value is `5 minutes` |
| 143 | +- This option specifies the longest time in waiting for dynamic scaling service endpoints, that to affect online clients at minimum. Normally the dynamic scale between single app server and a service endpoint can be finished in seconds, while considering if you have multiple app servers and multiple service endpoints with network jitter and would like to ensure client stability, you can configure this value accordingly. |
| 144 | + |
| 145 | +#### `MaxPollIntervalInSeconds` |
| 146 | + |
| 147 | +- Default value is `5` |
| 148 | +- This option defines the max poll interval allowed for `LongPolling` connections in Azure SignalR Service. If the next poll request doesn't come in within `MaxPollIntervalInSeconds`, Azure SignalR Service cleans up the client connection. Note that Azure SignalR Service also cleans up connections when cached waiting to write buffer size is greater than `1Mb` to ensure service performance. |
| 149 | +- The value is limited to `[1, 300]`. |
| 150 | + |
| 151 | +### Sample |
| 152 | + |
| 153 | +You can configure above options like the following sample code. |
| 154 | + |
| 155 | +```csharp |
| 156 | +services.AddSignalR() |
| 157 | + .AddAzureSignalR(options => |
| 158 | + { |
| 159 | + options.InitialHubServerConnectionCount = 10; |
| 160 | + options.AccessTokenLifetime = TimeSpan.FromDays(1); |
| 161 | + options.ClaimsProvider = context => context.User.Claims; |
| 162 | + |
| 163 | + options.GracefulShutdown.Mode = GracefulShutdownMode.WaitForClientsClose; |
| 164 | + options.GracefulShutdown.Timeout = TimeSpan.FromSeconds(10); |
| 165 | + }); |
| 166 | +``` |
| 167 | + |
| 168 | +## For the legacy ASP.NET SignalR |
| 169 | + |
| 170 | +> [!NOTE] |
| 171 | +> |
| 172 | +> If it is your first time trying SignalR, we recommend you use the [ASP.NET Core SignalR](/aspnet/core/signalr/introduction), it is **simpler, more reliable, and easier to use**. |
| 173 | + |
| 174 | +### Install the SDK |
| 175 | + |
| 176 | +Install SignalR Service SDK to your ASP.NET project with **Package Manager Console**: |
| 177 | + |
| 178 | +```powershell |
| 179 | +Install-Package Microsoft.Azure.SignalR.AspNet |
| 180 | +``` |
| 181 | + |
| 182 | +In your `Startup` class, use SignalR Service SDK as the following code snippet, replace `MapSignalR()` to `MapAzureSignalR({your_applicationName})`. Replace `{YourApplicationName}` to the name of your application, this is the unique name to distinguish this application with your other applications. You can use `this.GetType().FullName` as the value. |
| 183 | + |
| 184 | +```csharp |
| 185 | +public void Configuration(IAppBuilder app) |
| 186 | +{ |
| 187 | + app.MapAzureSignalR(this.GetType().FullName); |
| 188 | +} |
| 189 | +``` |
| 190 | + |
| 191 | +### Configure connection string |
| 192 | + |
| 193 | +Set the connection string in the `web.config` file, to the `connectionStrings` section: |
| 194 | + |
| 195 | +```xml |
| 196 | +<configuration> |
| 197 | + <connectionStrings> |
| 198 | + <add name="Azure:SignalR:ConnectionString" connectionString="Endpoint=...;AccessKey=..."/> |
| 199 | + </connectionStrings> |
| 200 | + ... |
| 201 | +</configuration> |
| 202 | +``` |
| 203 | + |
| 204 | +### Configure options |
| 205 | + |
| 206 | +There are a few [options](https://github.com/Azure/azure-signalr/blob/dev/src/Microsoft.Azure.SignalR.AspNet/ServiceOptions.cs) you can customize when using Azure SignalR Service SDK. |
| 207 | +
|
| 208 | +#### `ConnectionString` |
| 209 | + |
| 210 | +- Default value is the `Azure:SignalR:ConnectionString` `connectionString` or `appSetting` in `web.config` file. |
| 211 | +- It can be reconfigured, but make sure the value is **NOT** hard coded. |
| 212 | + |
| 213 | +#### `InitialHubServerConnectionCount` |
| 214 | + |
| 215 | +- Default value is `5`. |
| 216 | +- This option controls the initial count of connections per hub between application server and Azure SignalR Service. Usually keep it as the default value is enough. During runtime, the SDK might start new server connections for performance tuning or load balancing. When you have large number of clients, you can give it a larger number for better throughput. For example, if you have 100,000 clients in total, the connection count can be increased to `10` or `15`. |
| 217 | + |
| 218 | +#### `MaxHubServerConnectionCount` |
| 219 | + |
| 220 | +- Default value is `null`. |
| 221 | +- This option controls the max count of connections allowed per hub between application server and Azure SignalR Service. During runtime, the SDK might start new server connections for performance tuning or load balancing. By default a new server connection starts whenever needed. When the max allowed server connection count is configured, the SDK doesn't start new connections when server connection count reaches the limit. |
| 222 | + |
| 223 | +#### `ApplicationName` |
| 224 | + |
| 225 | +- Default value is `null`. |
| 226 | +- This option can be useful when you want to share the same Azure SignalR instance for different app servers containing the same hub names. If not set, all the connected app servers are considered to be instances of the same application. |
| 227 | + |
| 228 | +#### `ClaimProvider` |
| 229 | + |
| 230 | +- Default value is `null`. |
| 231 | +- This option controls what claims you want to associate with the client connection. |
| 232 | +It's used when Service SDK generates access token for client in client's negotiate request. |
| 233 | +By default, all claims from `IOwinContext.Authentication.User` of the negotiated request are reserved. |
| 234 | +- Normally you should leave this option as is. Make sure you understand what happens before customizing it. |
| 235 | + |
| 236 | +#### `AccessTokenLifetime` |
| 237 | + |
| 238 | +- Default value is `1 hour`. |
| 239 | +- This option controls the valid lifetime of the access token, which Service SDK generates for each client. |
| 240 | +The access token is returned in the response to client's negotiate request. |
| 241 | +- When `ServerSentEvent` or `LongPolling` is used as transport, client connection will be closed due to authentication failure after the expired time. |
| 242 | +You can increase this value to avoid client disconnect. |
| 243 | + |
| 244 | +#### `AccessTokenAlgorithm` |
| 245 | + |
| 246 | +- Default value is `HS256` |
| 247 | +- This option provides choice of [`SecurityAlgorithms`](https://github.com/AzureAD/azure-activedirectory-identitymodel-extensions-for-dotnet/blob/dev/src/Microsoft.IdentityModel.Tokens/SecurityAlgorithms.cs) when generate access token. Now supported optional values are `HS256` and `HS512`. Note that `HS512` is more secure but the generated token is comparatively longer than that using `HS256`. |
| 248 | +
|
| 249 | +#### `ServerStickyMode` |
| 250 | + |
| 251 | +- Default value is `Disabled`. |
| 252 | +- This option specifies the mode for **server sticky**. When the client is routed to the server that it first negotiates with, we call it **server sticky**. |
| 253 | +- In distributed scenarios, there can be multiple app servers connected to one Azure SignalR instance. As [internals of client connections](signalr-concept-internals.md#client-connections) explains, client first negotiates with the app server, and then redirects to Azure SignalR to establish the persistent connection. Azure SignalR then finds one app server to serve the client, as [Transport Data between client and server](signalr-concept-internals.md#data-transmission-between-client-and-server) explains. |
| 254 | + - When `Disabled`, the client routes to a random app server. In general, app servers have balanced client connections with this mode. If your scenarios are *broadcast* or *group send*, use this default option is enough. |
| 255 | + - When `Preferred`, Azure SignalR tries to find the app server that the client first negotiates with in a way that no other cost or global routing is needed. This one can be useful when your scenario is sent to connection*. *Send to connection* can have better performance and lower latency when the sender and the receiver are routed to the same app server. |
| 256 | + - When `Required`, Azure SignalR always tries to find the app server that the client first negotiates with. This option can be useful when some client context is fetched from `negotiate` step and stored in memory, and then to be used inside `Hub`s. However, this option might have performance drawbacks because it requires Azure SignalR to take other efforts to find this particular app server globally, and to keep globally routing traffics between client and server. |
| 257 | + |
| 258 | +#### `MaxPollIntervalInSeconds` |
| 259 | + |
| 260 | +- Default value is `5` |
| 261 | +- This option defines the max poll interval allowed for `LongPolling` connections in Azure SignalR Service. If the next poll request doesn't come in within `MaxPollIntervalInSeconds`, Azure SignalR Service cleans up the client connection. Note that Azure SignalR Service also cleans up connections when cached waiting to write buffer size is greater than `1Mb` to ensure service performance. |
| 262 | +- The value is limited to `[1, 300]`. |
| 263 | + |
| 264 | +### Sample |
| 265 | + |
| 266 | +You can configure above options like the following sample code. |
| 267 | + |
| 268 | +```csharp |
| 269 | +app.Map("/signalr",subApp => subApp.RunAzureSignalR(this.GetType().FullName, new HubConfiguration(), options => |
| 270 | +{ |
| 271 | + options.InitialHubServerConnectionCount = 1; |
| 272 | + options.AccessTokenLifetime = TimeSpan.FromDays(1); |
| 273 | + options.ClaimProvider = context => context.Authentication?.User.Claims; |
| 274 | +})); |
| 275 | +``` |
| 276 | + |
| 277 | +## Scale out application server |
| 278 | + |
| 279 | +With Azure SignalR Service, persistent connections are offloaded from application server so that you can focus on implementing your business logic in hub classes. |
| 280 | +But you still need to scale out application servers for better performance when handling massive client connections. |
| 281 | +Below are a few tips for scaling out application servers. |
| 282 | +- Multiple application servers can connect to the same Azure SignalR Service instance. |
| 283 | +- If you'd like to share the same Azure SignalR instance for different applications containing the same hub names, set them with different [ApplicationName](#applicationname) option. If not set, all the connected app servers are considered to be instances of the same application. |
| 284 | +- As long as the [ApplicationName](#applicationname) option and the name of the hub class is the same, connections from different application servers are grouped in the same hub. |
| 285 | +- Each client connection is only created in ***one*** of the application servers, and messages from that client are only sent to that same application server. If you want to access client information globally *(from all application servers)*, you have to use some centralized storage to save client information from all application servers. |
| 286 | + |
| 287 | +## Next steps |
| 288 | + |
| 289 | +In this article, you learn how to use SignalR Service in your applications. Check the following articles to learn more about SignalR Service. |
| 290 | + |
| 291 | +> [!div class="nextstepaction"] |
| 292 | +> [Azure SignalR Service internals](./signalr-concept-internals.md) |
| 293 | + |
| 294 | +> [!div class="nextstepaction"] |
| 295 | +> [Quickstart: Create a chat room by using SignalR Service](./signalr-quickstart-dotnet-core.md) |
0 commit comments