Skip to content

Instantly share code, notes, and snippets.

@sergofan
Created March 9, 2020 12:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sergofan/5be100c37a3dc635cf438c4ec02e4837 to your computer and use it in GitHub Desktop.
Save sergofan/5be100c37a3dc635cf438c4ec02e4837 to your computer and use it in GitHub Desktop.
// in startup.cs
using StackExchange.Redis;
public void ConfigureServices(IServiceCollection services)
{
ConfigurationOptions options = new ConfigurationOptions()
{
EndPoints = { { "remote.server.url", 6380 } },
Ssl = true,
Password = "password"
};
ConnectionMultiplexer connection = ConnectionMultiplexer.ConnectAsync(options).GetAwaiter().GetResult();
IDatabase db = connection.GetDatabase();
services.AddScoped<IDatabase>(_ => db);
}
// in namespace
using StackExchange.Redis;
namespace MyProject.MyNamespace
{
public interface IRedisService
{
Task<string> HandleRedisKey(RedisKey key, string val);
}
public class MyClass : IRedisService
{
private readonly IDatabase db;
public MyClass(IDatabase db)
{
this.db = db;
}
public async Task<string> HandleRedisKey(RedisKey key, string val)
{
RedisValue redisValue = await db.StringGetAsync(key);
if (redisValue.HasValue)
{
return redisValue;
}
else
{
db.StringSet(key, val);
return val;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment