Skip to content

Latest commit

 

History

History
280 lines (222 loc) · 15.1 KB

use-signalr-service.md

File metadata and controls

280 lines (222 loc) · 15.1 KB

Use Azure SignalR Service

Provision an Azure SignalR Service instance

Go to Azure Portal to provision a SignalR service instance.

Run ASP.NET CORE SignalR

1. Install and Use Service SDK

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");
    });
}

2. Configure Connection String

There are two approaches to configure SignalR Service's connection string in your application.

  • Set an environment variable with name Azure:SignalR:ConnectionString or Azure__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>);

3. Configure Service Options

There are a few options you can customize when using Azure SignalR Service SDK.

ConnectionCount

  • 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 or 15 for better throughput.

AccessTokenLifetime

  • 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 or LongPolling 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.

AccessTokenAlgorithm

  • Default value is HS256
  • This option provides choice of SecurityAlgorithms when generate access token. Now supported optional values are HS256 and HS512. Please note HS512 is more secure but the generated token will be comparatively longer than that using HS256.

ApplicationName

  • 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.

ClaimProvider

  • 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 at Hub.Context.User.
  • Normally you should leave this option as is. Make sure you understand what will happen before customizing it.

ServerStickyMode

  • 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 from negotiate step and stored in memory, and then to be used inside Hubs. 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.

GracefulShutdown

Mode
  • 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 in WaitForClientsClose, 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 and OnDisconnected will be triggered when connections be migrated in/out, and a IConnectionMigrationFeature will be set to help you determine if the connection has been migrated. Please visit our sample codes for detail usage.
Timeout
  • Default value is 30 seconds
  • This option specifies the longest time in waiting for clients to be closed/migrated.

ServiceScaleTimeout

  • 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.

MaxPollIntervalInSeconds

  • 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 within MaxPollIntervalInSeconds, 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 than 1Mb to ensure service performance.
  • The value is limited to [1, 300].

Sample

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);
            });

Run ASP.NET SignalR

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.

1. Install and Use Service SDK

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);
}

2. Configure Connection String

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>

3. Configure Service Options

There are a few options you can customize when using Azure SignalR Service SDK.

ConnectionCount

  • 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 or 15 for better throughput.

AccessTokenLifetime

  • 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 or LongPolling 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.

AccessTokenAlgorithm

  • Default value is HS256
  • This option provides choice of SecurityAlgorithms when generate access token. Now supported optional values are HS256 and HS512. Please note HS512 is more secure but the generated token will be comparatively longer than that using HS256.

ClaimProvider

  • 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.

ConnectionString

  • Default value is the Azure:SignalR:ConnectionString connectionString or appSetting in web.config file.
  • It can be reconfigured, but please make sure the value is NOT hard coded.

ServerStickyMode

MaxPollIntervalInSeconds

  • 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 within MaxPollIntervalInSeconds, 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 than 1Mb to ensure service performance.
  • The value is limited to [1, 300].

Sample

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;
}));

Scale Out Application Server

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.