Skip to content
Furkan Güngör edited this page Jan 2, 2021 · 1 revision

How to use EasyCache.Redis?

Installation

Install EasyCache.Redis from Nuget

Configuration

Use AddEasyRedisCache extension in startup.cs

Sample

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
    
    services.AddEasyRedisCache(options=>
    {
        options.Configuration = "localhost";
        options.InstanceName = GetType().Assembly.GetName().Name
    }); <-- Initialize EasyCache for Redis
}

Usage

Use IEasyCacheService from Dependency Injection.

Sample

private readonly IEasyCacheService easyCacheService;

public DefaultController(IEasyCacheService easyCacheService)
{
    this.easyCacheService = easyCacheService;
}

Example for Get

[HttpGet]
public async Task<IActionResult> GetAsync()
{
    string[] response = await easyCacheService.GetAsync("products");
    return Ok(response);
}

or

[HttpGet]
public IActionResult Get()
{
    string[] response = await easyCacheService.Get("products");
    return Ok(response);
}

Example for Remove

[HttpDelete("{id}")]
public async Task<IActionResult> DeleteAsync(int id)
{
    await easyCacheService.RemoveAsync(id.ToString());
    return NoContent();
}

or

[HttpDelete("{id}")]
public IActionResult Delete(int id)
{
    easyCacheService.Remove(id.ToString());
    return NoContent();
}

Example for Set

[HttpPost]
public async Task<IActionResult> SetAsync([FromBody] ExampleModel model)
{
    await easyCacheService.SetAsync("example",model,TimeSpan.FromMinutes(5));   
    return NoContent();
}

or

[HttpPost]
public IActionResult Set([FromBody] ExampleModel model)
{
    easyCacheService.Set("example",model,TimeSpan.FromMinutes(5));   
    return NoContent();
}
Clone this wiki locally