首页 技术 正文
技术 2022年11月20日
0 收藏 444 点赞 4,115 浏览 1679 个字

之前有写过一篇介绍c#操作redis的文章 http://www.cnblogs.com/axel10/p/8459434.html ,这篇文章中的案例使用了StringIncrement来实现了高并发情况下key值的稳定增加,但如果要用锁的方式而不是StringIncrement方法,那该怎么做呢?

LockTake涉及到三个参数:key,token和TimeSpan,分别表示redis数据库中该锁的名称、锁的持有者标识和有效时间。下面将用一个多线程增加key值的案例来演示LockTake/LockRelease的用法。

using StackExchange.Redis;
using StackExchange.Redis.Extensions.Core;
using StackExchange.Redis.Extensions.Core.Configuration;
using StackExchange.Redis.Extensions.Newtonsoft;
using System;
using System.Threading;namespace RedisTest
{
class Program
{
static RedisValue Token = Environment.MachineName;
static RedisKey Key = "lock"; static void Ins()
{
Thread thread = new Thread(() =>
{
for (int i = ; i < ; i++)
{ if (client.Database.LockTake(Key, Token, TimeSpan.MaxValue)) //key表示的是redis数据库中该锁的名称,不可重复。 Token用来标识谁拥有该锁并用来释放锁。TimeSpan表示该锁的有效时间。
{
try
{
int key = client.Get<int>("key"); client.Add("key", key + );
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
finally
{
client.Database.LockRelease(Key, Token);
}
}
else
{
Console.WriteLine("locking");
while (!TryAgain())
{
Thread.Sleep();
}
}
}
});
thread.Start();
} private static StackExchangeRedisCacheClient client; static void Main(string[] args)
{
var redisConfiguration = new RedisConfiguration() //配置
{
Hosts = new RedisHost[]
{
new RedisHost() {Host = "127.0.0.1", Port = }
}
}; client = new StackExchangeRedisCacheClient(new NewtonsoftSerializer(), redisConfiguration);
client.Add("key", ); for (int j = ; j < ; j++)
{
Ins();
} Thread.Sleep(); int i = client.Get<int>("key");
Console.WriteLine(i);
Console.ReadKey();
} static bool TryAgain(int value)
{
if (client.Database.LockTake(Key, Token, TimeSpan.MaxValue))
{
try
{
int key = client.Get<int>("key"); client.Add("key", key + value);
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
finally
{
client.Database.LockRelease(Key, Token);
} return true;
}
else
{
return false;
}
}
}
}
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,077
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,552
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,400
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,176
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,813
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,896