public static bool SetLock(string key, int val, TimeSpan timeOut)
{
using (IRedisClient rds = prcm.GetClient())
{
using (rds.AcquireLock("Lock" + key, timeOut))
{
int v = rds.Get(key);
return rds.Set(key, v + val);
}
}
}
using ServiceStack.Redis;
using ServiceStack.Redis.Generic;
using ServiceStack.Text;
using Sim.Common;
using System.Threading;
namespace ConsoleTest
{
class Program
{
static void Main(string[] args)
{
//启动2进程模拟 redis并发锁情况
Redis.Set("u", 1);
RedisConcurrence r1 = new RedisConcurrence("T1");
Thread thread1 = new Thread(new ThreadStart(r1.Go));
thread1.Start();
RedisConcurrence r2 = new RedisConcurrence("T2");
Thread thread2 = new Thread(new ThreadStart(r2.Go));
thread2.Start();
}
}
public class RedisConcurrence
{
private string key = "u";
///
/// 操作次数
///
private int count = 10;
///
/// 锁定时间(秒)
///
private int lockTime = 5;
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
public RedisConcurrence(string name)
{
this.name = name;
}
public void Go()
{
TimeSpan time = new TimeSpan(0, 0, 0, this.lockTime);
for (var i = 0; i < this.count; i++)
{
Redis.SetLock(key, 1, time);
Console.WriteLine(this.name + ":" + DateTime.Now.ToString() + " " + Redis.Get(key).ToString());
}
}
}
}
运行结果(刚开始有2个一样的数据,属于正常情况,自己想吧)