Redis Distributed lock
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace RedisDemo
{
class Program
{
static void Main(string[] args)
{
TestRedisLockWithFencingToken();
Console.ReadKey();
}
public static List<int> SLEEP_OF_SECONDS = new List<int> { 20, 0, 0, 10, 10 };
public static void TestRedisLockWithFencingToken()
{
var tasks = new List<Task>();
var mockService = new MockService();
Enumerable.Range(1, 3).ToList().ForEach(it =>
{
var task = Task.Run(() =>
{
var taskId = $"task_{it}";
var lockHelper = new RedisLockHelper();
var lockKey = "article:1";
try
{
Console.WriteLine($"-> {taskId} begin acquire redis lock.");
var result = lockHelper.GetLock(lockKey, TimeSpan.FromSeconds(10));
if (result.Success)
{
var taskInfo = new TaskInfo { TaskId = taskId, FencingToken = result.FencingToken ?? 0 };
Console.WriteLine($"-> {taskId} acquire lock success {taskInfo}.");
var sleepOfSeconds = SLEEP_OF_SECONDS[it - 1];
Thread.Sleep(sleepOfSeconds * 1000);
mockService.Save(taskInfo);
Console.WriteLine($"{taskInfo} Done");
}
}
catch (Exception ex)
{
Console.WriteLine($"{taskId} {ex.Message}");
}
finally
{
lockHelper.ReleaseLock("article:1");
}
});
tasks.Add(task);
});
try
{
Task.WaitAll(tasks.ToArray());
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
}
}
}
public class TaskInfo
{
public long FencingToken { get; set; }
public string TaskId { get; set; }
public override string ToString()
{
return $"TaskId: {TaskId} - FencingToken: {FencingToken}";
}
}
public class MockService
{
private IConnectionMultiplexer connection;
private String fencingTokenKey = "redis_fencingToken";
public MockService()
{
this.Initialize();
}
private void Initialize()
{
connection = ConnectionMultiplexer.Connect("localhost");
}
public void Close()
{
if (connection != null)
{
connection.Close();
}
}
public void Save(TaskInfo taskInfo)
{
Console.WriteLine($"MockService#Save: {taskInfo}");
var fencingToken = taskInfo.FencingToken;
var serverFencingToken = connection.GetDatabase().StringGet(fencingTokenKey);
Console.WriteLine($"MockService#Save: {taskInfo} - Server Fencing Token {serverFencingToken}");
if (serverFencingToken.HasValue)
{
if (fencingToken == (long)serverFencingToken)
{
Console.WriteLine($"MockService#Save: {taskInfo} Save Success.");
}
else
{
Console.WriteLine($"MockService#Save: {taskInfo} Save Failure, Fencingtoken not equal server token.");
}
}
else
{
Console.WriteLine($"{taskInfo} Save error");
}
}
}
public class RedisLockResult
{
public bool Success { get; set; }
public long? FencingToken { get; set; }
}
public class RedisLockHelper : IDisposable
{
private IConnectionMultiplexer connection;
private String value;
private String fencingTokenKey = "redis_fencingToken";
public RedisLockHelper()
{
value = Guid.NewGuid().ToString();
this.Initialize();
}
public RedisLockResult GetLock(String key, TimeSpan expiry)
{
var db = connection.GetDatabase();
var lockSuccess = db.StringSet(key, value, expiry, When.NotExists, CommandFlags.None);
var start = DateTime.Now;
while (!lockSuccess)
{
Thread.Sleep(50);
lockSuccess = db.StringSet(key, value, expiry, When.NotExists, CommandFlags.None);
start = start.AddMilliseconds(50);
if (DateTime.Now.Subtract(start).TotalSeconds > 20)
{
throw new InvalidOperationException($"can not acquire distributed lock");
}
}
var result = new RedisLockResult()
{
Success = lockSuccess
};
if (lockSuccess)
{
var fencingToken = db.StringIncrement(fencingTokenKey, 1, CommandFlags.None);
result.FencingToken = fencingToken;
}
return result;
}
public void ReleaseLock(RedisKey key)
{
var lua = @"if redis.call('get', @key) == @value then
return redis.call('del', @key)
else
return 0
end";
var db = connection.GetDatabase();
var prepare = LuaScript.Prepare(lua);
var result = db.ScriptEvaluate(prepare, new { key = key, value = value });
}
private void Initialize()
{
connection = ConnectionMultiplexer.Connect("localhost");
}
public void Dispose()
{
if (connection != null)
{
connection.Dispose();
}
}
}
}
Redis Distributed lock的更多相关文章
- distributed lock manager (DLM)(分布式管理锁)
A distributed lock manager (DLM) provides distributed software applications with a means to synchron ...
- ZooKeeper Distributed lock
https://segmentfault.com/a/1190000016351095 http://www.dengshenyu.com/java/%E5%88%86%E5%B8%83%E5%BC% ...
- jedisLock—redis分布式锁实现
一.使用分布式锁要满足的几个条件: 系统是一个分布式系统(关键是分布式,单机的可以使用ReentrantLock或者synchronized代码块来实现) 共享资源(各个系统访问同一个资源,资源的载体 ...
- nopCommerce 3.9 大波浪系列 之 使用Redis主从高可用缓存
一.概述 nop支持Redis作为缓存,Redis出众的性能在企业中得到了广泛的应用.Redis支持主从复制,HA,集群. 一般来说,只有一台Redis是不可行的,原因如下: 单台Redis服务器会发 ...
- Redlock(redis分布式锁)原理分析
Redlock:全名叫做 Redis Distributed Lock;即使用redis实现的分布式锁: 使用场景:多个服务间保证同一时刻同一时间段内同一用户只能有一个请求(防止关键业务出现并发攻击) ...
- Redis实战(九)Redis的典型应用场景
序言 数据缓存 共享Session 分布式锁 https://www.cnblogs.com/wangrudong003/p/10627539.html Redlock(redis分布式锁)原理分析 ...
- jedisLock—redis分布式锁实现(转)
一.使用分布式锁要满足的几个条件: 系统是一个分布式系统(关键是分布式,单机的可以使用ReentrantLock或者synchronized代码块来实现) 共享资源(各个系统访问同一个资源,资源的载体 ...
- springboot实现分布式锁(spring integration,redis)
Springboot实现分布式锁(Spring Integration+Redis) 一.在项目的pom.xml中添加相关依赖 1)Spring Integration依赖 <dependenc ...
- Dapr v1.8 正式发布
Dapr是一套开源.可移植的事件驱动型运行时,允许开发人员轻松立足云端与边缘位置运行弹性.微服务.无状态以及有状态等应用程序类型.Dapr能够确保开发人员专注于编写业务逻辑,而不必分神于解决分布式系统 ...
随机推荐
- openlayers图层加标注
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title&g ...
- 安装Elasticsearch到Linux(源码)
运行环境 系统版本:CentOS Linux release 7.3.1611 (Core) 软件版本:Elasticsearch-7.1.0 硬件要求:最低2核4GB 安装过程 1.源码安装JDK ...
- 51Nod 1284 2 3 5 7的倍数 (容斥定理)
给出一个数N,求1至N中,有多少个数不是2 3 5 7的倍数. 例如N = 10,只有1不是2 3 5 7的倍数. Input 输入1个数N(1 <= N <= 10^18). Outpu ...
- JDK下载安装与环境变量配置图文教程【超详细】
JDK下载安装与环境变量配置图文教程[超详细] 创建时间:2019年11月13日11时02分 文章目录 1. JDK介绍 1.1 什么是JDK? 1.2 JDK版本介绍 2. JDK下载与安装 3.w ...
- 问题 E: Problem B
#include <cstdio> #include <cstring> #include <algorithm> #include <vector> ...
- 【PHP】使用PHP抓取Bing每日图像并为己所用
Bing搜索的首页每天都会推送一张很漂亮的图片,把它保存下来,当做电脑桌面或是自己的网站背景图还不是美滋滋…… 今天的bing图片是这样的 既然要抓取这张图片,首先就得弄清这张图是从何而来的.经过对必 ...
- layui radio手动选择失效的问题
var radio_types = document.getElementsByName("radio_type"); for (var i = 0; i < radio_t ...
- python3练习100题——049
题目:使用lambda来创建匿名函数. sum=lambda x,y:x+y from functools import reduce reduce(sum,[1,2,3,4,5])
- 135.在django中操作cookie
操作cookie 设置cookie 设置cookie是设置值给浏览器的,因此我们可以通过response的对象来设置,可以通过HttpResponse的对象或者是HttpResponseBase的子类 ...
- cssflex兼容(横向顶边对齐)
display: flex; display: -webkit-box; display: -moz-box; display: -ms-flexbox; display: -webkit-flex; ...