- Use Azure SignalR Service
Go to Azure Portal to provision a SignalR service instance.
Run below command to install SignalR Service SDK to your ASP.NET Core project.
dotnet add package Microsoft.Azure.SignalR --version 1.0.*
In your Startup
class, use SignalR Service SDK as the following code snippet.
public void ConfigureServices(IServiceCollection services)
{
services.AddSignalR()
.AddAzureSignalR();
}
public void Configure(IApplicationBuilder app)
{
app.UseAzureSignalR(routes =>
{
routes.MapHub<YourHubClass>("/path_for_your_hub");
});
}
There are two approaches to configure SignalR Service's connection string in your application.
-
Set an environment variable with name
Azure:SignalR:ConnectionString
orAzure__SignalR__ConnectionString
.- In Azure App Service, put it in application settings.
-
Pass the connection string as a parameter of
AddAzureSignalR()
as below sample codes.services.AddSignalR() .AddAzureSignalR(<replace with your connection string>);
or
services.AddSignalR() .AddAzureSignalR(options => options.ConnectionString = <replace with your connection string>);
There are a few options you can customize when using Azure SignalR Service SDK.
- Default value is
5
. - This option controls the count of connections between application server and Azure SignalR Service.
The default value will be performant enough most of the time.
You can increase it for better performance if the total client count is too big.
For example, if you have 100,000 clients in total, the connection count can be increased to
10
or15
for better throughput.
- Default value is
1 hour
. - This option controls the valid lifetime of the access token, which is generated by Service SDK for each client. The access token is returned in the response to client's negotiate request.
- When
ServerSentEvent
orLongPolling
is used as transport, client connection will be closed due to authentication failure after the expire time. You can increase this value to avoid client disconnect.
- Default value is
HS256
- This option provides choice of
SecurityAlgorithms
when generate access token. Now supported optional values areHS256
andHS512
. Please noteHS512
is more secure but the generated token will be comparatively longer than that usingHS256
.
- Default value is
null
. - 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.
- Default value is
null
. - This option controls what claims you want to associate with the client connection.
It will be used when Service SDK generates access token for client in client's negotiate request.
By default, all claims from
HttpContext.User
of the negotiate request will be reserved. They can be accessed atHub.Context.User
. - Normally you should leave this option as is. Make sure you understand what will happen before customizing it.
- Default value is
Disabled
. - This option specifies the mode for server sticky. When the client is routed to the server which it first negotiates with, we call it server sticky.
- In distributed scenarios, there can be multiple app servers connected to one Azure SignalR instance. As internals of 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 explains.
- 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. - When
Preferred
, Azure SignalR tries to find the app server which the client first negotiates with in a way that no additional cost or global routing is needed. This one can be useful when your scenario is send 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. - When
Required
, Azure SignalR always tries to find the app server which the client first negotiates with. This options can be useful when some client context is fetched fromnegotiate
step and stored in memory, and then to be used insideHub
s. However, this option may have performance drawbacks because it requires Azure SignalR to take additional efforts to find this particular app server globally, and to keep globally routing traffics between client and server.
- When
- Default value is
Off
- This option specifies the behavior after the app server receives a CTRL+C (SIGINT).
- When set to
WaitForClientsClose
, instead of stopping the server immediately, we remove it from the ASRS to prevent new client connections from being assigned to this server. - When set to
MigrateClients
, in addition to the steps we mentioned inWaitForClientsClose
, we will try migrating client connections to another valid server at a proper time. We could make sure the migration will only happen on the message boundaries, which means each of old/new servers will receive intact messages.OnConnected
andOnDisconnected
will be triggered when connections be migrated in/out, and aIConnectionMigrationFeature
will be set to help you determine if the connection has been migrated. Please visit our sample codes for detail usage.
- Default value is
30 seconds
- This option specifies the longest time in waiting for clients to be closed/migrated.
- Default value is
5 minutes
- 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.
- Default value is
5
- This option defines the max poll interval allowed for
LongPolling
connections in Azure SignalR Service. If the next poll request does not come in withinMaxPollIntervalInSeconds
, Azure SignalR Service cleans up the client connection. Note that Azure SignalR Service will also clean up connections when cached waiting to write buffer size is greater than1Mb
to ensure service performance. - The value is limited to
[1, 300]
.
You can configure above options like the following sample code.
services.AddSignalR()
.AddAzureSignalR(options =>
{
options.ConnectionCount = 10;
options.AccessTokenLifetime = TimeSpan.FromDays(1);
options.ClaimsProvider = context => context.User.Claims;
option.GracefulShutdown.Mode = GracefulShutdownMode.WaitForClientsClose;
option.GracefulShutdown.Timeout = TimeSpan.FromSeconds(10);
});
If it is your first time trying SignalR, we recommend you to use the ASP.NET Core SignalR, it is simpler, more reliable, and easier to use.
Install SignalR Service SDK to your ASP.NET project with Package Manager Console:
Install-Package Microsoft.Azure.SignalR.AspNet
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.
public void Configuration(IAppBuilder app)
{
app.MapAzureSignalR(this.GetType().FullName);
}
Set the connection string in the web.config
file, to the connectionStrings
section:
<configuration>
<connectionStrings>
<add name="Azure:SignalR:ConnectionString" connectionString="Endpoint=...;AccessKey=..."/>
</connectionStrings>
...
</configuration>
There are a few options you can customize when using Azure SignalR Service SDK.
- Default value is
5
. - This option controls the count of connections per hub between application server and Azure SignalR Service.
The default value will be performant enough most of the time.
You can increase it for better performance if the total client count is too big.
For example, if you have 100,000 clients in total, the connection count can be increased to
10
or15
for better throughput.
- Default value is
1 hour
. - This option controls the valid lifetime of the access token, which is generated by Service SDK for each client. The access token is returned in the response to client's negotiate request.
- When
ServerSentEvent
orLongPolling
is used as transport, client connection will be closed due to authentication failure after the expire time. You can increase this value to avoid client disconnect.
- Default value is
HS256
- This option provides choice of
SecurityAlgorithms
when generate access token. Now supported optional values areHS256
andHS512
. Please noteHS512
is more secure but the generated token will be comparatively longer than that usingHS256
.
- Default value is
null
. - This option controls what claims you want to associate with the client connection.
It will be used when Service SDK generates access token for client in client's negotiate request.
By default, all claims from
IOwinContext.Authentication.User
of the negotiate request will be reserved. - Normally you should leave this option as is. Make sure you understand what will happen before customizing it.
- Default value is the
Azure:SignalR:ConnectionString
connectionString
orappSetting
inweb.config
file. - It can be reconfigured, but please make sure the value is NOT hard coded.
- Default value is
Disabled
. - Refer to ServerStickyMode for details.
- Default value is
5
- This option defines the max poll interval allowed for
LongPolling
connections in Azure SignalR Service. If the next poll request does not come in withinMaxPollIntervalInSeconds
, Azure SignalR Service cleans up the client connection. Note that Azure SignalR Service will also clean up connections when cached waiting to write buffer size is greater than1Mb
to ensure service performance. - The value is limited to
[1, 300]
.
You can configure above options like the following sample code.
app.Map("/signalr",subApp => subApp.RunAzureSignalR(this.GetType().FullName, new HubConfiguration(), options =>
{
options.ConnectionCount = 1;
options.AccessTokenLifetime = TimeSpan.FromDays(1);
options.ClaimProvider = context => context.Authentication?.User.Claims;
}));
With Azure SignalR Service, persistent connections are offloaded from application server. It only has to take care of business logics in your hub classes. But you still need to scale out application servers for better performance when handling massive client connections. Below are a few tips for scaling out application servers.
- Multiple application servers can connect to the same Azure SignalR Service instance.
- As long as name of the hub class is the same, connections from different application servers are grouped in the same hub.
- Each client connection will only be created in one of the application servers, and messages from that client will only be sent to the same application server.
- If you want to access client information globally (from all application servers), you have to use some storage to save client information from all application servers.