How do I not need to request the api all the time?

Asked

Viewed 64 times

1

I’m a beginner in development. net core and I am developing an application that consumes data from an api and shows to users, but I need to update the site all the time and it takes a little time.

Is there any way I can store the return of the api temporarily somewhere?

Pagemodel class, which requests the api:

public class IndexModel : PageModel
{
  public Global Global { get; private set; }
  public Country[] Countries { get; private set; }

  public async Task OnGetAsync()
  {
    try
    {
      var create = RestService.For<IGetRootobject>("https://api.covid19api.com/summary");
      var result = await create.GetAsync(); // ou var result = create.GetAsync().GetAwaiter().GetResult();
      Global = result.Global;
      Countries = result.Countries;
    }
    catch (Exception e)
    {
      _logger.LogInformation("Erro na requisição http: " + e.Message);
    }
  }
}

1 answer

2


The simplest can be used the Cache in-memory in ASP.NET Core (translation: Memory cache) that can be configured in seconds, minutes, days, etc. its permanence in the information memory, that is, according to your need.

To enable this code in your project on startup.cs in the method ConfigureServices call the extension method .AddMemoryCache() as shown in the code:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMemoryCache(); // adicione essa linha para funciona cache em memoria
    services.AddRazorPages();
}

is now enabled to be used in Pages Razor and how you are in a battle in a few questions (1 and 2) follows the same example below:

Add a property:

public IMemoryCache MemoryCache { get; private set; }

then in the construtor of his PageModel pass to interface and assign the property previously created for the injection that is passed in the construtor:

public MostrarModel(IMemoryCache memoryCache)
{
    MemoryCache = memoryCache;
}

from this has the possibility to create cache of the information in the memory of any type and by a simple decision structure can seek the value in the cache or create the value and store in cache for an amount of time (in the case example just below the full code was added thirty minutes, but as has already been reported by being configured days and hours its way):

Final code:

public class MostrarModel : PageModel
{
    public Country[] Countries { get; private set; }        
    public IMemoryCache MemoryCache { get; private set; } // cache
    public MostrarModel(IMemoryCache memoryCache) // injeção
    {
        MemoryCache = memoryCache; // atribuição
    }
    public async Task OnGetAsync()
    {
        //chave do cache (cada valor armazenado tem a sua) 
        string key = "countries_cache";
        //verificando se o valor está ou não em cache e tomando as medidas
        //dependendo da decisão na estrutura
        if (!MemoryCache.TryGetValue<Country[]>(key, out Country[] values))
        {
            var create = RestService
                .For<IGetRootobject>("https://api.covid19api.com/summary");
            var result = await create.GetAsync();
            Countries = result.Countries;
            //Armazenando em cache
            MemoryCache.Set(key, Countries, System.TimeSpan.FromMinutes(30));
        } 
        else
        {
            //recuperando do cache
            Countries = values;
        }
    }
}

The other way is with Distributed caching in ASP.NET Core that in this case is information shared on multiple servers that greatly improves performance and scalability and its configuration is similar to the previous:

Add the extension method:

services.AddDistributedMemoryCache();

and in the constructor and in the code are very similar to the previous

private readonly Idistributedcache Memorycache;

public MostrarModel(IDistributedCache memoryCache)
{
    MemoryCache = memoryCache;
}

and with the methods GetAsync to recover and SetAsync to record the cache.


Several types still exist as:

  • Which would be the most recommended? Cache in-memory in ASP.NET Core or Distributed caching in ASP.NET Core ?

  • You can use in-memory cache @eduardonogueira

Browser other questions tagged

You are not signed in. Login or sign up in order to post.