Skip to content

Commit d950f76

Browse files
committed
Update Distributed cache topic+sample
Updates Updates Updates Updates Updates
1 parent 2ef24f3 commit d950f76

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

66 files changed

+24430
-271
lines changed

aspnetcore/fundamentals/app-state.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ Session state exhibits the following behaviors:
6464
6565
The in-memory cache provider stores session data in the memory of the server where the app resides. In a server farm scenario:
6666

67-
* Use *sticky sessions* to tie each session to a specific app instance on an individual server. [Azure App Service](https://azure.microsoft.com/services/app-service/) uses [Application Request Routing (ARR)](/iis/extensions/planning-for-arr/using-the-application-request-routing-module) to enforce sticky sessions by default. However, sticky sessions can affect scalability and complicate web app updates. A better approach is to use a Redis or SQL Server distributed cache, which doesn't require sticky sessions. For more information, see [Work with a distributed cache](xref:performance/caching/distributed).
67+
* Use *sticky sessions* to tie each session to a specific app instance on an individual server. [Azure App Service](https://azure.microsoft.com/services/app-service/) uses [Application Request Routing (ARR)](/iis/extensions/planning-for-arr/using-the-application-request-routing-module) to enforce sticky sessions by default. However, sticky sessions can affect scalability and complicate web app updates. A better approach is to use a Redis or SQL Server distributed cache, which doesn't require sticky sessions. For more information, see <xref:performance/caching/distributed>.
6868
* The session cookie is encrypted via [IDataProtector](/dotnet/api/microsoft.aspnetcore.dataprotection.idataprotector). Data Protection must be properly configured to read session cookies on each machine. For more information, see [Data Protection in ASP.NET Core](xref:security/data-protection/index) and [Key storage providers](xref:security/data-protection/implementation/key-storage-providers).
6969

7070
### Configure session state
@@ -81,7 +81,7 @@ The [Microsoft.AspNetCore.Session](https://www.nuget.org/packages/Microsoft.AspN
8181

8282
::: moniker-end
8383

84-
* Any of the [IDistributedCache](/dotnet/api/microsoft.extensions.caching.distributed.idistributedcache) memory caches. The `IDistributedCache` implementation is used as a backing store for session. For more information, see [Work with a distributed cache](xref:performance/caching/distributed).
84+
* Any of the [IDistributedCache](/dotnet/api/microsoft.extensions.caching.distributed.idistributedcache) memory caches. The `IDistributedCache` implementation is used as a backing store for session. For more information, see <xref:performance/caching/distributed>.
8585
* A call to [AddSession](/dotnet/api/microsoft.extensions.dependencyinjection.sessionservicecollectionextensions.addsession) in `ConfigureServices`.
8686
* A call to [UseSession](/dotnet/api/microsoft.aspnetcore.builder.sessionmiddlewareextensions#methods_) in `Configure`.
8787

@@ -428,7 +428,7 @@ Use [Dependency Injection](xref:fundamentals/dependency-injection) to make data
428428

429429
* "Unable to resolve service for type 'Microsoft.Extensions.Caching.Distributed.IDistributedCache' while attempting to activate 'Microsoft.AspNetCore.Session.DistributedSessionStore'."
430430

431-
This is usually caused by failing to configure at least one `IDistributedCache` implementation. For more information, see [Work with a distributed cache](xref:performance/caching/distributed) and [Cache in-memory](xref:performance/caching/memory).
431+
This is usually caused by failing to configure at least one `IDistributedCache` implementation. For more information, see <xref:performance/caching/distributed> and <xref:performance/caching/memory>.
432432

433433
* In the event that the session middleware fails to persist a session (for example, if the backing store isn't available), the middleware logs the exception and the request continues normally. This leads to unpredictable behavior.
434434

aspnetcore/fundamentals/primitives/change-tokens.md

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -189,9 +189,9 @@ var compositeChangeToken =
189189

190190
## Additional resources
191191

192-
* [Cache in-memory](xref:performance/caching/memory)
193-
* [Work with a distributed cache](xref:performance/caching/distributed)
194-
* [Response caching](xref:performance/caching/response)
195-
* [Response Caching Middleware](xref:performance/caching/middleware)
196-
* [Cache Tag Helper](xref:mvc/views/tag-helpers/builtin-th/cache-tag-helper)
197-
* [Distributed Cache Tag Helper](xref:mvc/views/tag-helpers/builtin-th/distributed-cache-tag-helper)
192+
* <xref:performance/caching/memory>
193+
* <xref:performance/caching/distributed>
194+
* <xref:performance/caching/response>
195+
* <xref:performance/caching/middleware>
196+
* <xref:mvc/views/tag-helpers/builtin-th/cache-tag-helper>
197+
* <xref:mvc/views/tag-helpers/builtin-th/distributed-cache-tag-helper>

aspnetcore/performance/caching/distributed.md

Lines changed: 102 additions & 71 deletions
Large diffs are not rendered by default.

aspnetcore/performance/caching/distributed/sample/src/DistCacheSample/Program.cs

Lines changed: 0 additions & 20 deletions
This file was deleted.

aspnetcore/performance/caching/distributed/sample/src/DistCacheSample/Properties/launchSettings.json

Lines changed: 0 additions & 27 deletions
This file was deleted.

aspnetcore/performance/caching/distributed/sample/src/DistCacheSample/StartTimeHeader.cs

Lines changed: 0 additions & 48 deletions
This file was deleted.

aspnetcore/performance/caching/distributed/sample/src/DistCacheSample/Startup.cs

Lines changed: 0 additions & 64 deletions
This file was deleted.
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
@page
2+
@model ErrorModel
3+
@{
4+
ViewData["Title"] = "Error";
5+
}
6+
7+
<h1 class="text-danger">Error.</h1>
8+
<h2 class="text-danger">An error occurred while processing your request.</h2>
9+
10+
@if (Model.ShowRequestId)
11+
{
12+
<p>
13+
<strong>Request ID:</strong> <code>@Model.RequestId</code>
14+
</p>
15+
}
16+
17+
<h3>Development Mode</h3>
18+
<p>
19+
Swapping to the <strong>Development</strong> environment displays detailed information about the error that occurred.
20+
</p>
21+
<p>
22+
<strong>The Development environment shouldn't be enabled for deployed applications</strong>. It can result in displaying sensitive information from exceptions to end users. For local debugging, enable the Development environment by setting the <strong>ASPNETCORE_ENVIRONMENT</strong> environment variable to <strong>Development</strong> and restarting the app or adding <code>.UseEnvironment("Development")</code> to <code>WebHost</code> in <i>Program.cs</i> and restarting the app.
23+
</p>
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
using System.Diagnostics;
2+
using Microsoft.AspNetCore.Mvc;
3+
using Microsoft.AspNetCore.Mvc.RazorPages;
4+
5+
namespace SampleApp.Pages
6+
{
7+
public class ErrorModel : PageModel
8+
{
9+
public string RequestId { get; set; }
10+
11+
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
12+
13+
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
14+
public void OnGet()
15+
{
16+
RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier;
17+
}
18+
}
19+
}
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
@page
2+
@model IndexModel
3+
@{
4+
ViewData["Title"] = "Distributed Cache Sample";
5+
}
6+
7+
<h1>@ViewData["Title"]</h1>
8+
9+
<div class="row">
10+
<div class="col-md-8">
11+
<form method="post">
12+
<div class="panel panel-default">
13+
<div class="panel-heading clearfix">
14+
<button type="submit" asp-page-handler="ResetCachedTime" class="pull-right btn btn-danger">Reset Cached Time</button>
15+
<h3 class="panel-title" style="line-height:2.1">Cached Time (UTC)</h3>
16+
</div>
17+
<div class="panel-body">
18+
<p>The current time is: @DateTime.UtcNow.ToString()</p>
19+
<p>The cached time is: @Model.CachedTimeUTC</p>
20+
</div>
21+
</div>
22+
</form>
23+
</div>
24+
</div>
25+
26+
<div class="row">
27+
<div class="col-md-8">
28+
<div class="panel panel-default">
29+
<div class="panel-heading">
30+
<h3 class="panel-title">Instructions</h3>
31+
</div>
32+
<div class="panel-body">
33+
<p>When the app starts, the current time is cached (key = <code>cachedTimeUTC</code>) with a 20 second sliding expiration.</p>
34+
<p>Each time this page is loaded, the cache is checked for the cached time. If the cached time hasn't expired, the time is displayed.</p>
35+
<p>If 20 seconds have elapsed since the last time the cached time was accessed (the last time this page was loaded), the page displays <code>Cached Time Expired</code>.</p>
36+
<p>The cached time can be updated immediately to the current time by selecting the <b>Reset Cached Time</b> button.</p>
37+
<p>In the Development environment, the sample uses the Distributed Memory Cache and doesn't require an external cache service.</p>
38+
<h4>Distributed SQL Server Cache</h4>
39+
<p>To activate the sample to use a Distributed SQL Server Cache:</p>
40+
<ol>
41+
<li>Create a SQL Server database. The sample specifies <code>DistCache</code> in the <code>DistCache_ConnectionString</code> in the <em>appsettings.Production.json</em> file.</li>
42+
<li>Create a table to hold cached values. The sample specifies <code>TestCache</code> in <code>Startup.ConfigureServices</code> where <code>AddDistributedSqlServerCache</code> is called to register distributed caching services. The schema (<code>dbo</code>) is also set.</li>
43+
<li>Update the <code>DistCache_ConnectionString</code> in the <em>appsettings.Production.json</em> file to point to the SQL Server instance, database, and table. If you use the default database name, schema, and table name, you only need to update the SQL Server instance (<code>(localdb)\\MSSQLLocalDB</code>).</li>
44+
<li>Set the <code>ASPNETCORE_ENVIRONMENT</code> environment variable to <code>Production</code>. In the Production environment, the app uses the Distributed SQL Server Cache when it starts.</li>
45+
</ol>
46+
<h4>Distributed Redis Cache</h4>
47+
<p>This sample can be changed to use a Distributed Redis Cache:</p>
48+
<ol>
49+
<li>
50+
Swap the Distributed SQL Server Cache service registration (<code>AddDistributedSqlServerCache</code>) in <code>Startup.ConfigureServices</code> with Redis service registrations:
51+
<pre><code>services.AddDistributedRedisCache(options =>
52+
{
53+
options.Configuration = "localhost";
54+
options.InstanceName = "SampleInstance";
55+
});</code></pre>
56+
</li>
57+
<li>Install Redis on your local machine: Install the <a href="https://chocolatey.org/packages/redis-64/">Redis Chocolatey package</a> and run <code>redis-server</code> from a command prompt.</li>
58+
<li>Set the <code>ASPNETCORE_ENVIRONMENT</code> environment variable to <code>Production</code>. In the Production environment, the app uses the Distributed Redis Cache when it starts.</li>
59+
</ol>
60+
</div>
61+
</div>
62+
</div>
63+
</div>
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Threading.Tasks;
4+
using Microsoft.AspNetCore.Mvc;
5+
using System.Text;
6+
using Microsoft.AspNetCore.Mvc.RazorPages;
7+
using Microsoft.Extensions.Caching.Distributed;
8+
9+
namespace SampleApp.Pages
10+
{
11+
#region snippet_IndexModel
12+
public class IndexModel : PageModel
13+
{
14+
private readonly IDistributedCache _cache;
15+
16+
public IndexModel(IDistributedCache cache)
17+
{
18+
_cache = cache;
19+
}
20+
21+
public string CachedTimeUTC { get; set; }
22+
23+
public async Task OnGetAsync()
24+
{
25+
CachedTimeUTC = "Cached Time Expired";
26+
var encodedCachedTimeUTC = await _cache.GetAsync("cachedTimeUTC");
27+
28+
if (encodedCachedTimeUTC != null)
29+
{
30+
CachedTimeUTC = Encoding.UTF8.GetString(encodedCachedTimeUTC);
31+
}
32+
}
33+
34+
public async Task<IActionResult> OnPostResetCachedTime()
35+
{
36+
var currentTimeUTC = DateTime.UtcNow.ToString();
37+
byte[] encodedCurrentTimeUTC = Encoding.UTF8.GetBytes(currentTimeUTC);
38+
var options = new DistributedCacheEntryOptions()
39+
.SetSlidingExpiration(TimeSpan.FromSeconds(20));
40+
await _cache.SetAsync("cachedTimeUTC", encodedCurrentTimeUTC, options);
41+
42+
return RedirectToPage();
43+
}
44+
}
45+
#endregion
46+
}

0 commit comments

Comments
 (0)