"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

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

  • Modern cloud engineering will help you stay one step ahead of the competition. Find out how reading the post in a few minutes may improve your company's future and make it many times better by clicking for more. The article is a vast repository of knowledge from which everyone will learn something crucial for themselves.

  • Hello! Don't know how to expand your team and introduce new staff to your business? Our company has been specializing in staff recruitment services for many years and will help you hire the best specialists who have the necessary knowledge and skills for your business!

  • Hello! To hire a cool angular developer, you need to pay attention to his skills in the javascript programming language, in addition to skills with angular. To correctly select a developer for your project click now where our consultants will help you in choosing a candidate and tell you what to look for.

  • Hello! An important part of every project is COCO annotations. Hiring a good Common Object in Context specialist can be time-consuming for every company. Our agency will help you find reliable and specialized COCO annotators for your needs! Go to our website for more details!

  • Every day will bring profit, and the company will be more competitive, if you put effort into the development of a project or product. Companies that have already had the opportunity to independently use the high-quality BOT model are satisfied with the results and already their business is flourishing and profits are growing.

  • Hi guys. Good Microsoft developers need to be familiar with different schemes and programs, meaning different programming languages. Developers should also be familiar with software development methodologies, such as Agile and Scrum, as well as with database design and management. I found out about this on an excellent informative resource.

  • Hello! Lidar annotation is a time-consuming process and when choosing a real specialist for your team, you need to be very selective and demanding. But it is not always easy to find the right specialist and you can spend too much time on it. Our agency has been providing lidar annotation services for many years and we provide only the best specialists!

  • Hi everyone! Speech annotation is the process of detecting and classifying sounds for machine learning and AI applications. We can assist with several types of speech classification, such as: music classification, ambient sound classification and natural language utterance classification. Are you ready to boost your project with high-quality voice annotation services? Talk to us and explore the details.

  • Hiring a qualified IT specialist is not an easy task, because now there are many specialists in this field who do not have sufficient knowledge and experience. But this responsible and professional team of IT specialists has never let anyone down, professional marketing such option can be provided to you. You can expect fast work, high-quality results, with such an offer you can't waste time. For more info check url here!

  • Hiring a qualified IT specialist is not an easy task, because now there are many specialists in this field who do not have sufficient knowledge and experience. But this responsible and professional team of IT specialists has never let anyone down, professional marketing such option can be provided to you. You can expect fast work, high-quality results, with such an offer you can't waste time. For more info check on this site!

  • The best option to start your search for your specialist or the whole team to annotate data is this site, where you will see information about all the questions you are interested in and all the pitfalls, I strongly recommend that you devote just a few minutes of your time to this, because this article can serve as an excellent foundation for your successful future.

  • While using a comma checker can save time and effort for the writer. Rather than spending time manually reviewing their writing for comma errors, they can rely on the checker to quickly identify and highlight any issues. This can be especially helpful for writers who are not confident in their comma usage or who are working on a tight deadline. Follow the link for more information!

    Source: https://www.commacorrector.com/master-complex-punctuation-with-comma-and-semicolon-checker/

  • Greetings, writers! Writing is a critical part of communication in both personal and professional settings. Writing without errors is essential to convey one's ideas effectively. Online services that help you find and correct errors in your writing can be an excellent resource to ensure that your work is error-free and professional. <a href=https://www.prepositionfinder.com/examples-of-what-can-be-fixed-with-preposition-identifier/>Click here now</a>

  • Greetings, writers! Writing is a critical part of communication in both personal and professional settings. Writing without errors is essential to convey one's ideas effectively. Online services that help you find and correct errors in your writing can be an excellent resource to ensure that your work is error-free and professional. Click here now
    Source: https://www.prepositionfinder.com/examples-of-what-can-be-fixed-with-preposition-identifier/

  • If you're having trouble at work or school due to a lack of grammar, this free online proofreading service can help. Which is quick, clear, and efficient. You will be able to save time and nerves while also improving your grammar knowledge. As a result, don't wait any longer and dive right into this field of useful knowledge. For more information, go check out the network right now!

  • When writing texts, it's not always possible to dedicate the time and focus necessary to proofread and make corrections. Thankfully, there's a web-based copywriting tool that can do just that in mere seconds. The added advantage is that this software is completely free and incredibly user-friendly.

  • Hello! Our Ukrainian outsourcing company provides quality outsourced image annotation services for your project. The specialists we provide have an extensive set of skills and are able to cope with any task. Do not waste time and hire the best specialists right now!

  • Hello! Are you looking for an entity in an annotation text a service to train your AI or machine learning, or do you already have a training team but are bad at linking between entities or describing them poorly? Then we will provide you with the best specialists to solve these problems. Our specialists will bring your AI training to a new quality level.

  • The technique of emphasizing necessary things on a picture or in a video is known as image and video annotation. There are numerous benefits to hiring Remote Annotation Specialists, including: a properly functioning business plan, swift and high-quality work, a customized approach for your specific project and industry, and increased productivity and effectiveness of your company. Contact us as soon as possible to begin a partnership with us and have your company operating smoothly.

  • Hello! Go to our website to get the best document labeling services in just 4 steps! Just fill out the form on our website and share your requirements, get an estimate from us and after payment we will start cooperation. Our specialists have extensive experience and can help your project!

  • Good day everyone! I would like to advise you to outsource annotation services. We know you need high-quality and accurate annotations to ensure long-term customers and ongoing business. Therefore, this content will help you learn more about our services, which will guarantee your success.

  • Good day everyone! I would like to advise you to outsource annotation services. We know you need high-quality and accurate annotations to ensure long-term customers and ongoing business. Therefore, this content will help you learn more about our services, which will guarantee your success.
    https://www.linelabeling.com/

  • [url=https://en.wikipedia.org/]English Wikipedia[/url]

  • Hello! Outsourcing PDF tagging is one way to speed up document processing and reduce staff costs. Our company offers a full range of manual PDF tagging services. We will provide you with the best processors ready to perform any task related to PDF tagging!

  • Hello friends! If your goal is to annotate your images in order to improve the quality of their recognition by artificial intelligence, then I can recommend a company that specializes in this. They use a variety of modern methods, and do an excellent job of the task! Just <a href="https://www.pictureannotation.com/">click to explore</a>!

  • Annotation services can help a company develop professional expertise in several ways like improved accuracy in AI models. CVAT annotation services can provide accurate and high-quality annotations for training AI models. This can help a company develop more accurate and reliable AI models, which can improve their expertise in computer vision and machine learning.

  • Greetings to all forum members! If you're looking to improve your business's online presence, it's crucial to hire a semantic text analysis specialist. These experts use cutting-edge tools to analyze the meaning and context of your text, helping you to understand what your customers want and how to give it to them.

  • If you are introducing new and most importantly innovative data annotation services to your company then you should be aware of all aspects of data processing and how AI-assisted data tagging can make this task much easier for you. <a href="https://www.humanannotation.com/ai-assisted-labeling-for-data-processing/">explore the details</a> at this link and elevate your company to a whole new level!

  • If you are introducing new and most importantly innovative data annotation services to your company then you should be aware of all aspects of data processing and how AI-assisted data tagging can make this task much easier for you. Explore the details at this link and elevate your company to a whole new level!

  • Services in the field of data labeling are sufficient, but specialists are always in short supply. If your business, project, startup, faced this problem and you need a service in a specific case, for example, Speech Recognition, then you should try an excellent service that is the best of the best. The company will provide you with the best team of data labeling professionals virtually. You will select a team according to the size depending on the volume of your business or you can choose yourself.

  • Services in the field of data labeling are sufficient, but specialists are always in short supply. If your business, project, startup, faced this problem and you need a service in a specific case, for example, Speech Recognition, then you should try an excellent service that is the best of the best. The company will provide you with the best team of data labeling professionals virtually. You will select a team according to the size depending on the volume of your business or you can choose yourself.

  • It is not necessary to spend a lot of time searching and interviewing potential candidates for work in your company. You can easily find a COCO Annotation specialist today by simply following the link and reading a short and useful article. You will definitely be satisfied with the result, so click and see more details!

  • Searching for a trustworthy and affordable method to label your data for machine learning applications? We offer access to a pool of highly skilled developers that focus on data labeling and machine learning in addition to a variety of data labeling tools and services. In order to ensure that your data is labeled appropriately and successfully, our developers may collaborate with you to design bespoke labeling solutions that address your unique demands and objectives. Why then wait? Check it here to have access to our trained developers' knowledge right away!

  • The fast evolving demands of the IT business may be too much for conventional hiring techniques to handle. Your capacity to quickly change your staffing levels to accommodate shifting company needs is made possible by outsourcing's flexibility and scalability. Still want to know more about outsourcing? Then you will be surprised by amount of info on this page!

  • Are you struggling to find the right talent for your data annotation needs? Look no further than our outsourcing services. We provide access to a wide range of data labeling professionals who can help your business unlock the full potential of its data. Our experts are well-versed in various annotation tools and techniques, ensuring top-quality results every time.

  • Hello! Increase efficiency and accuracy in your work with our text annotation services. Our highly qualified specialists work as a team to ensure high quality abstracts and fast results. We specialize in various industries and our specialists solve any tasks of text annotation. Go to our website to find out more!

  • Free AI Essay Writer is a valuable resource for individuals seeking writing assistance without the financial burden. This tool harnesses the power of artificial intelligence to generate essays efficiently and effectively, free ai essay writer provides users with a platform to express their thoughts and ideas, offering suggestions and guidance along the way. It's a great option for students and writers on a budget, allowing them to access professional-level writing assistance at no cost.

  • From the enchanting Old Town with its narrow alleys and intricate architecture to the pristine beaches that stretch along the Indian Ocean, Mombasa never fails to leave a lasting impression . <a href="https://www.exclusivetravel.co/destinations/africa/kenya/mombasa/mombasa_gallery/mombasa-pics-index7.html">Mombasa Kenya</a>.

  • Good to read the detail of Distributed Cache with SQL Server in ASP.Net Core application and it is very helpful for the developers to find such resources where they can learn how to make the best codes in a short time.

  • Unlock the power of seamless connectivity and entertainment with Spectrum Triple Play! Get high-speed internet, crystal-clear cable TV, and feature-packed phone services all bundled into one, making your digital world simpler and more enjoyable than ever.

  • <a href="https://electromartindia.xyz/">clickhere</a>

  • Optimize your ASP.Net Core app's performance with SQL Server and distributed caching. Efficiently manage frequently accessed data, reducing database load and enhancing response times. Seamlessly integrate SQL Server for swift data retrieval, ensuring a responsive user experience. Boost scalability and handle increased traffic effortlessly with this powerful combination.

  • A nova atualização do CS2, lançada em 14 de fevereiro de 2024, trouxe diversas mudanças e melhorias para o jogo. Entre as principais novidades, estão:

    Novos mapas:

    Cache: O mapa clássico foi completamente refeito com gráficos atualizados e jogabilidade aprimorada.
    Anubis: Um novo mapa competitivo foi adicionado ao jogo.
    Melhorias na jogabilidade:

    Movimento: O movimento do jogador foi aprimorado para ser mais fluido e responsivo.
    Armas: As armas foram rebalanceadas para melhorar a competitividade do jogo.
    Sons: Os sons do jogo foram remasterizados para serem mais realistas e imersivos.
    Outras mudanças:

    Novo sistema de matchmaking: O sistema de matchmaking foi reformulado para criar partidas mais justas e equilibradas.
    Novas skins: Novas skins para armas e personagens foram adicionadas ao jogo.
    Melhorias na interface: A interface do jogo foi aprimorada para ser mais intuitiva e fácil de usar.

  • The game offers a smooth and enjoyable gaming experience.

  • Tracking diversity in recruiting software involves monitoring metrics like gender, ethnicity, and age of applicants and <a href="https://www.cabletvandinternetpackages.com/cheap-cable-and-internet-packages/">cheap internet and cable package</a> hires. Utilizing such tools facilitates data-driven decision-making, ensuring companies foster inclusive hiring practices. Beyond statistics, it promotes accountability and guides strategies for creating diverse, equitable, and inclusive workplaces.

  • The Sentence Counter is a powerful and user-friendly tool that helps writers, editors, students, and content creators achieve better writing outcomes by providing instant and accurate sentence counts. It’s perfect for refining your work, ensuring compliance with guidelines, and improving overall writing quality.

  • Keep up the good work. Really enjoyed your post. Thanks from RailsCarma


  • GameSkill - Guias, Dicas, Tutoriais e Reviews - Aprimore suas habilidades nos jogos com tutoriais detalhados, dicas e estratégias para FPS, MMORPG e outros gêneros. Descubra tudo no GameSkill e torne-se um mestre dos games.

    Aprimore suas habilidades nos jogos com tutoriais detalhados, dicas e estratégias para FPS, MMORPG e outros gêneros. Descubra tudo no GameSkill e torne-se um mestre dos games.

Add a Comment

As it will appear on the website

Not displayed

Your website