Caching is used to stored frequently used data or calculated values to reduce recalculation, fetching data from DB server, which improves performance of application.
ASP.Net Core provides an interface IDistributedCache which exposes APIs to implement caching.
Useful IDistributedCache Methods :
GetString(key)
GetStringAsync(key)
SetString(key, value, options)
SetStringAsync(key,value, options)
Refresh(key)
RefreshAsync(key)
Remove(key)
RemoveAsync(key)
Caching service stores data in Key-Value pairs we can set value for a given key and retrieve value by key from Cache.
We can pass options in SetStrings methods which is object of DistributedCacheEntryOptions class.
DistributedCacheEntryOptions class has following useful methods:
AbsoluteExpiration : used to specify an absolute expiry date.
AbsoluteExpirationRelativeToNow : used to specify a relative expiry date.
SlidingExpiration : used to specify a period of inactivity, after which the
item will be ejected from the cache if it hasn’t been read.
How to Add data to Cache: below code sets (string) key and (string) value in Cache for 2 min.
await cache.SetStringAsync("cacheKey", "String_val_to_Cache"
new DistributedCacheEntryOptions {
AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(2)
});
How to Configure Distributed Caching Service: To use distributed cache service we need to configure in Program.cs
builder.Services.AddDistributedMemoryCache(opts => {
opts.SizeLimit = 200;
});
DistributedMemoryCache is an implementation of
IDistributedCache which is added in service collection by AddDistributedMemoryCache(), I will add In-Memory caching functionality to the application. There are two other implementations available using appropriate NuGet packages.
AddDistributedSqlServerCache: sets up a cache that stores data in SQL Server. Nuget: Microsoft.Extensions.Caching.SqlServer
AddStackExchangeRedisCache: This method sets up a Redis cache
Nuget: Microsoft.Extensions.Caching.Redis
Note: AddDistributedMemoryCache stores data in Memory so it would not be sharable among other applications.(only it has distributed in it's name:))
AddDistributedSqlServerCache method stores the cache data in a SQL Server database, which
can be shared between multiple ASP.NET Core servers and which stores the data persistently.
Steps to use DistributedSqlServerCache:
1. you can create a new Database for caching specific or use your existing database with new table.
2.Need to configure DistributedSqlServerCache similar to DistributedMemotyCache with connection, Database and table details, see the below code:
Adding connection string If, new DB created for caching
"ConnectionStrings": {
"CacheConnection": "Server=(localdb)\\MSSQLLocalDB;Database=CachingDb"
}
Adding caching service in DI Service collection:
builder.Services.AddDistributedSqlServerCache(opts => {
opts.ConnectionString
= builder.Configuration["ConnectionStrings:CacheConnection"]
opts.SchemaName = "dbo";
opts.TableName = "DataCache";
});
Inject IDistributedCache in component where you want to use caching.
Note:When you use the IDistributedCache service, the data values are shared between all requests. If you want to cache different data values for each user, then you can use the session middleware. The session middleware relies on the IDistributedCache service to store its data, which means that session data will be stored persistently and be available to a distributed application when the AddDistributedSqlServerCache method is used.
Response Caching:
Caching entire response may be a good idea instead of caching individual item, especially in case of UI. Caching responses requires the addition of
a service and a middleware component.
Adding services:
builder.Services.AddResponseCaching();
builder.Services.AddSingleton();
Using Services:
app.UseResponseCaching();
Note: The response caching feature does not use the IDistributedCache service. Responses are
cached in memory and are not distributed.
Example: (copy and paste below code in any editor)
public class TestResponseCaching{
public async Task Endpoint(HttpContext context, IDistributedCache cache,
IResponseFormatter formatter, LinkGenerator generator) {
int count;
int.TryParse((string?)context.Request.RouteValues["count"],
out count);
long total = 0;
for (int i = 1; i <= count; i++) {
total += i;
}
string totalString = $"({ DateTime.Now.ToLongTimeString() }) {total}";
context.Response.Headers["Cache-Control"] = "public, max-age=120";
string? url = generator.GetPathByRouteValues(context, null,
new { count = count });
await formatter.Format(context,
$" ({DateTime.Now.ToLongTimeString()}) Total for {count}"
+ $" values:{totalString} "
+ $"
Reload");
}
}
Cache-Control header is used to control response caching. The middleware will only cache
responses that have a Cache-Control header that contains the public directive. The max-age directive is
used to specify the period that the response can be cached for, expressed in seconds.
Response Compressing: ASP.NET Core includes middleware that will compress responses for browsers that have
indicated they can handle compressed data. The middleware is added to the pipeline with the
UseResponseCompression method. Compression is a trade-off between the server resources
required for compression and the bandwidth required to deliver content to the client, and it should not
be switched on without testing to determine the performance impact.
No comments:
Post a Comment