"Knowledge has to be improved, challenged, and increased constantly, or it vanishes."

Distributed Cache with SQL Server in ASP.Net Core application

Performance is a key factor for any application, especially for web & mobile applications. Based on various research studies, it has been identified that high performing sites retain users than low performing sites. This means a poor performing site will have impact on the company’s business goals. So, Developers, be aware to make sure your applications are designed for faster response times.

One of the aspects that affect the performance of an application is Caching. With caching, you store the frequently accessed data and store in some temporary storage, As a developer, you should carefully consider the various caching mechanisms and implement them in your applications.

Caching in ASP.Net Application

ASP.Net supports both In-Memory Cache and Distributed Cache. Let me illustrate the basic differences.

In-Memory Cache

In-Memory Cache, your application uses Server memory to store the cached data. This works perfectly if you have only one server. In today’s world, where you use cloud services and automatically scale your applications, all your servers need to access the cached data from a single source, and In-Memory cache will not help you here,

Distributed Cache

In distributed cache, the cached data is stored and shared across all servers. ASP.Net supports several types of distributed cache implementations such as SQL Server, Redis, NCache etc.

In this article, I am going to demonstrate how to implement distributed cache with SQL Server. For the purpose of this demo, I created a .Net application using the template “ASP.Net Core Web App”. The screenshot of the app in solution explorer is given below.

clip_image002

Since we are going to use SQL Server distributed cache, install the following Nuget package.

Microsoft.Extensions.Caching.SqlServer

clip_image004

Once the Nuget package is installed, the next step is to install the tooling support for sql-cache in .net CLI, so that we can generate the required tables. From Visual Studio, open the package manager console and enter the following command.

dotnet tool install -g dotnet-sql-cache

clip_image006

With this command the dotnet-sql-cache will be installed globally (-g switch) in your computer. If for any reason, if you want to uninstall you may use the following command.

dotnet tool uninstall -g dotnet-sql-cache

Now you can use the tool to create the database table where you will be storing the cache entries.

dotnet sql-cache create "Your Connection String" dbo CacheTable

To the sql-cache create command, you need to pass your connection string, the schema and the table name. A table with the given table name and schema will be created in the target database.

clip_image008

The following is the schema of the table that is created by the dotnet tool.

clip_image010

If you don’t want to use the tool to create your database, you can use the following SQL script to create the cache table.


CREATE TABLE [dbo].[CacheTable](
	[Id] [nvarchar](449) NOT NULL,
	[Value] [varbinary](max) NOT NULL,
	[ExpiresAtTime] [datetimeoffset](7) NOT NULL,
	[SlidingExpirationInSeconds] [bigint] NULL,
	[AbsoluteExpiration] [datetimeoffset](7) NULL,
PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

Let us configure the app to use distributed cache. First we need to add the distributed cache to the Services using the Method AddDistributedSqlServerCache, so that it will be available for dependency injection.


builder.Services.AddDistributedSqlServerCache(options =>
{
    options.ConnectionString = builder.Configuration.GetConnectionString("CacheConnectionString");
    options.SchemaName = "dbo";
    options.TableName = "CacheTable";
});

CacheConnectionstring is the connection string I defined in the appsettings.json file. The schema name and the table name are the ones we passed to the dotnet tool.

Now Let us see how the caching working in razor pages. In the PageModel class, in the OnGet handler, the application will check for a cache entry, and if not found, it will get the data from the GetData method. For demonstration purpose, I added a 5 seconds sleep to the method, in real time, this will be a method that fetches data from database or some other data sources. Once the data is retrieved for the first time, it will be added to the cache entry with a sliding expiration. For the subsequent requests, the data will be fetched from the cache. See the code for my PageModel below.


using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Caching.Distributed;
using System.Text;

namespace DistributedCacheSample.Pages
{
    public class IndexModel : PageModel
    {
        private readonly ILogger _logger;

        private readonly IDistributedCache Cache;
        public string? Data { get; set; }
        public DateTime StartTime { get; set; }

        public DateTime CompletedTime { get; set; }
        public IndexModel(ILogger logger, IDistributedCache cache)
        {
            _logger = logger;
            Cache = cache;
        }

        public async Task OnGetAsync()
        {
            StartTime = DateTime.Now;
            byte[] encodedData = await Cache.GetAsync("MyCacheKey");
            if (encodedData != null)
            {
                Data = Encoding.UTF8.GetString(encodedData);
            }
            else
            {
                // Data is not there in cache. So build it. 
                Data = await GetData();;
                encodedData = Encoding.UTF8.GetBytes(Data);
                var options = new DistributedCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromSeconds(50));
                await Cache.SetAsync("MyCacheKey", encodedData, options);
            }
            CompletedTime = DateTime.Now;
        }

        private Task GetData()
        {
            Thread.Sleep(5000);
            return Task.FromResult("BIG DATA");
        }
    }
}

The code is self explanatory. The GetData method returns the string “Big Data” after 5 seconds and OnGet handler will add it to the cache. Now let us see the razor markup in the cshtml page. The start time and completed time variables are updated with the current time at the start and end respectively.


<div class="text-center">
    <h1 class="display-4">@Model.Data</h1>
    <p>Start Time: @Model.StartTime.ToString("dd-MM-yyyy HH:mm:ss:ffff")</p>
    <p>Completed Time: @Model.CompletedTime.ToString("dd-MM-yyyy HH:mm:ss:ffff")</p>
</div>

Now let us run the application, for the first time. You may notice the 5 seconds difference between start time and completed time.

clip_image012

Now let us run the application again, and you will see there is no more waiting. The data is fetched from the cache.

clip_image014

Now the database contains the cache value with the Id of the key you defined.

clip_image016

Implementing Distributed Cache in ASP.Net web application is relatively easy and developers can make use of the caching implementation to ensure the applications run faster.

References:

https://docs.microsoft.com/en-us/aspnet/core/performance/caching/overview?view=aspnetcore-6.0

https://docs.microsoft.com/en-us/aspnet/core/performance/caching/distributed?view=aspnetcore-6.0

4 Comments

  • O jogo sempre providencia um tempo para que o jogador compre seu armamento utilizando o dinheiro ganho durante a competição. Deve-se ter em mente sempre que, quanto mais abates e assistências o jogador tiver, melhores serão as recompensas. A premissa básica do jogo é, simplesmente, eliminar a equipe inimiga. Por outro lado, também é possível vencer a rodada ao plantar uma bomba, e defendê-la por 45 a 35 segundos. Caso esteja buscando os melhores sites para apostar em partidas de CS:GO, você encontrará a melhor lista aqui na CSGObets.

  • Em 13 de agosto de 2013, teve uma atualização onde foram adicionados itens no cs go, como skins de armas, que foram adicionados em uma grande atualização, um update nomeado "negócio de armas". A maioria dos itens de skins são recebidos de forma aleatória ao fim da partida e podem ser adquiridas por caixas, com chaves que podem ser comprados através do próprio game, semelhante aos sistemas de obtenção de itens em Team Fortress 2 e Dota 2. Esses itens também podem ser negociados entre os jogadores através do sistema de trocas da Valve ou pelo Mercado da Comunidade Steam.

    Em outubro de 2014, uma atualização acrescentou kits de música, que substituem o padrão de música in-game com música a partir de trilha sonora de artistas encomendados pela Valve. Se um jogador com um kit equipado música torna-se jogador mais valioso da rodada, sua música vai tocar para os outros no final da rodada. Há um recurso para permitir kits para ser emprestado, e kits podem ser vendidas e trocados através do mercado da comunidade steam para csgo

  • Opa, sou novo no cenário do CS:GO e tenho muitas dúvidas sobre o jogo e gostaria da opinião dos mais experientes da comunidade:

    A skins de cs go mudam alguma coisa na gameplay?
    Por que as skins de cs são tão caras?
    Tem como melhorar o desempenho e fps do cs no meu computador?
    Quanto tempo jogando é suficiente para sair da patente prata?
    Sites de skins, onde as pessoas abrem caixas e apostam, por exemplo, como funciona.
    Pesquisei um pouco e achei um site que me ajudou, mas não sei se essas apostas são realmente seguras.
    Se alguma boa alma puder ajudar, ficarei agradecido :)

  • Lease age. It is one of the quickest developing proptech patterns in the lodging business. It is about the change in inclination from claiming to leasing land, putting the interest for rental units in front of purchasing. The pattern encourages the quick improvement of vertical investment properties and, thus, the increment of the land advancement organizations. The rising client interest for innovation. Present day customers need a client experience they have some control over according to the convenience point of view. They need to control access, temperature, lights, and more through helpful advanced channels, like cell phones. Proptech can convey such a computerized insight. Also, because of artificial intelligence and augmented reality, it can definitely further develop the client experience while making due, picking, involving any property for rent recharging, exchanges, building the executives, and that's just the beginning.

Add a Comment

As it will appear on the website

Not displayed

Your website