Skip to content

Instantly share code, notes, and snippets.

@Chriz76
Created July 10, 2021 19:50
Show Gist options
  • Save Chriz76/b576fd5c2b8c648af3f54dabe59a5a96 to your computer and use it in GitHub Desktop.
Save Chriz76/b576fd5c2b8c648af3f54dabe59a5a96 to your computer and use it in GitHub Desktop.
public void PusblishOutstandingPosts(CancellationToken stoppingToken)
{
const string script = @"if tonumber(redis.call('ZADD', @key1, @timestamp, @value)) == 0 then
return redis.call('GET', @key2)
else
return redis.call('INCR', @key2)
end";
var prepared = LuaScript.Prepare(script);
var cache = _muxer.GetDatabase();
for (int i = 0; i < _connectionStrings.Count; i++)
{
cache.StringGet("Shard:" + i + ":LastPostId").TryParse(out long lastPostId);
using var dbContext = new PostServiceContext(_connectionStrings[i]);
foreach (var post in dbContext.Post.Where(p => p.PostId > (int)lastPostId).OrderBy(p => p.PostId))
{
var res = prepared.Evaluate(cache, new {
key1 = (RedisKey)"{User:" + post.UserId +"}:PostsByTimestamp",
key2 = (RedisKey)"{User:" + post.UserId + "}:PostCount",
timestamp = post.TimeStamp.ToString(),
value = post.PostId.ToString()});
cache.Execute("ZADD", new object[] { "UsersByPostCount", "GT", int.Parse(res.ToString()), post.UserId }, CommandFlags.FireAndForget);
lastPostId = post.PostId;
}
cache.StringSet("Shard:" + i + ":LastPostId", lastPostId);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment