Giter Site home page Giter Site logo

poc.redis's Introduction

PocRedis

POC usando dotnet e Redis como cache.

Criação de ambiente

Criar um Redis localmente com docker:

docker run -p 6379:6379 --name redis -d redis

Configuração do appsettings.json

Adicionar à lista de ConnectionStrings:

"ConnectionStrings": {
    "Redis": "localhost:6379,ssl=false,abortConnect=false",

    // Exemplo AWS
    // "host.da.aws.region.cache.amazonaws.com:6379,password=sua-senha-secreta,ssl=true,abortConnect=false
}

Configuração da aplicação

1- Adicionar a lib abaixo ao projeto:

Microsoft.Extensions.Caching.StackExchangeRedis

2- Configurar o container de injeção de dependência para usar o Redis como provedor de IDistributedCache.

var redisConnectionString = builder.Configuration.GetConnectionString("Redis");

if (redisConnectionString == null)
{
    // Se não houver connectionString de Redis, usa cache em memória.
    builder.Services.AddDistributedMemoryCache();
}
else
{
    builder.Services.AddStackExchangeRedisCache(s =>
    {
        s.Configuration = redisConnectionString;
        
        // Isso é um prefixo que será adicionado às keys (tanto Get quanto Set).
        s.InstanceName = "poc-redis:"; 
    });
}

3- Feito isso, basta usar a interface IDistributedCache nos serviços.

public class CacheTestController : ControllerBase
{

    private readonly ILogger<CacheTestController> _logger;
    private readonly IDistributedCache _distributedCache;

    private const string cacheKey = "key-teste";

    public CacheTestController(ILogger<CacheTestController> logger, IDistributedCache distributedCache)
    {
        _logger = logger;
        _distributedCache = distributedCache;
    }

    [HttpGet, Route("ler")]
    public async Task<ActionResult> GetAsync()
    {
        var cacheValue = await _distributedCache.GetStringAsync(cacheKey);

        if (cacheValue == null)
            return NotFound($"Não foi encontrado valor no cache. Key: [{cacheKey}]");

        return Ok(cacheValue);
    }

    [HttpPost, Route("gravar")]
    public async Task<ActionResult> AddAsync(string valor, int duracaoSegundos)
    {
        await _distributedCache.SetStringAsync(cacheKey, valor, new DistributedCacheEntryOptions
        {
            AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(duracaoSegundos)
        });

        return Ok($"Valor gravado no cache. Key: [{cacheKey}]");
    }
}

4- Para visualizar os dados que estão sendo gravados no cache, pode ser usado o Another Redis Desktop Manager.

poc.redis's People

Contributors

rodolfo-souza avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.