Skip to content

Instantly share code, notes, and snippets.

@aeinbu
Created September 28, 2015 13:16
Show Gist options
  • Save aeinbu/c0275951eb9564e1ddae to your computer and use it in GitHub Desktop.
Save aeinbu/c0275951eb9564e1ddae to your computer and use it in GitHub Desktop.
Simple extension to make it easier to use Redis Caching and StackExchange.Redis package
using System;
using StackExchange.Redis;
namespace ConsoleApplication1
{
public static class RedisExtensions
{
public static RedisValue Get(this IDatabase db, RedisKey key, Func<RedisValue> loadFunc, TimeSpan slidingDuration)
{
var ret = db.StringGet(key);
if (!ret.HasValue)
{
ret = loadFunc();
db.Set(key, ret, slidingDuration);
}
else
{
// sliding expiration
db.KeyExpire(key, slidingDuration, CommandFlags.FireAndForget);
}
return ret;
}
public static void Set(this IDatabase db, RedisKey key, RedisValue newValue, TimeSpan slidingDuration)
{
db.StringSet(key, newValue, slidingDuration, When.Always, CommandFlags.FireAndForget);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment