Aller au contenu

Redis

De Banane Atomic

Connection from ASP.NET

Program.cs
var redisConnectionString = configuration.GetConnectionString("Redis") ?? throw new ConfigurationKeyNotFoundException("ConnectionString:Redis");
var redisPassword = configuration.GetValue<string>("RedisPwd");

services.AddStackExchangeRedisCache(options =>
{
    options.ConfigurationOptions = new ConfigurationOptions
    {
        EndPoints = { redisConnectionString },
        Password = redisPassword,
        Ssl = true
    };
    options.InstanceName = "MyApp:";
});

// if the Redis cache server is not reachable locally, use a distributed memory cache instead
services.AddDistributedMemoryCache();
MyService.cs
public class MyService(IDistributedCache distributedCache) : IMyService
{
    private readonly DistributedCacheEntryOptions distributedCacheEntryOptions = new()
    {
        SlidingExpiration = TimeSpan.FromDays(7)
    };

    public async Task<List<ItemResponse>> GetItemsAsync(GetItemsQuery query)
    {
        var cacheKey = GetCacheReferenceKey(query);
        var cachedValue = await distributedCache.GetStringAsync(cacheKey);
        if (cachedValue != null)
            return JsonSerializer.Deserialize<List<ItemResponse>>(cachedValue);

        var items = await itemProvider.GetItemsAsync(query);
        var serializedItems = JsonSerializer.Serialize(items);
        await distributedCache.SetStringAsync(cacheKey, serializedItems, distributedCacheEntryOptions);

        return items;
    }

    private static string GetCacheReferenceKey(object o)
    {
        var jsonData = JsonSerializer.Serialize(o);
        return $"cache:GetItemsQuery:{Convert.ToBase64String(Encoding.UTF8.GetBytes(jsonData))}";
    }
}

Redis CLI

# authentication
AUTH [password]

# list databases
INFO keyspace

# select database 0
select 0

# flush the current database
flushdb async

# list all the keys
keys *