这篇文章主要介绍了C#中如何使用redis,文中示例代码非常详细,帮助大家更好的理解和学习,感兴趣的朋友可以了解下
redis 是一个非关系型高性能的key-value数据库。和Memcached类似,它支持存储的value类型相对更多,包括string(字符串)、list(链表)、set(集合)、zset(sorted set --有序集合)和hash(哈希类型)。这些数据类型都支持push/pop、add/remove及取交集并集和差集及更丰富的操作,而且这些操作都是原子性的。在此基础上,redis支持各种不同方式的排序。与memcached一样,为了保证效率,数据都是缓存在内存中。区别的是redis会周期性的把更新的数据写入磁盘或者把修改操作写入追加的记录文件,并且在此基础上实现了master-slave(主从)同步。
下面介绍下,在C#中如何使用redis
1、引用 StackExchange.Redis
public class RedisHelper
{
private static ConnectionMultiplexer multiplexer { get; set; }
static RedisHelper()
{
}
public static IDatabase GetDataBase(int dbNums = 1)
{
if (multiplexer == null)
Init();
return multiplexer.GetDatabase(dbNums);
}
public static ConnectionMultiplexer GetMultiplexer()
{
if (multiplexer == null)
Init();
return multiplexer;
}
public static bool IsConnect(string key, IDatabase redisDb, string module, string action)
{
if (!redisDb.IsConnected(key))
{
LogHelper.Error("current redis is not connect", null, module, action);
return false;
}
return true;
}
private static void Init()
{
try
{
var configString = ConfigurationManager.AppSettings["RedisConfigString"];
ConfigurationOptions options = ConfigurationOptions.Parse(configString);
multiplexer = ConnectionMultiplexer.Connect(options);
}
catch (Exception ex)
{
LogHelper.Error(ex, "RedisHelper", "Static");
}
}
}
3、常用操作
IDatabase _cacheClient = RedisHelper.GetDataBase(4);
//key是否存在
_cacheClient.KeyExists("key")
//设置key-vaule
_cacheClient.StringSet("key", "value");
//设置过期时间
_cacheClient.KeyExpire("key", TimeSpan.FromMinutes(1));
//删除
_cacheClient.KeyDelete("key");
4、redis 虽然也可以做消息队列,实现也简单,但弊端同样明显,不推荐
//发布
ConnectionMultiplexer multiplexer = RedisHelper.GetMultiplexer();
ISubscriber sub = multiplexer.GetSubscriber();
var queue = sub.Publish("channel name", "message");
//订阅
ConnectionMultiplexer multiplexer = RedisHelper.GetMultiplexer();
ISubscriber sub = multiplexer.GetSubscriber();
sub.Subscribe("channel name", (channel, message) =>
{
//TODO
});
5、计数器,用于秒杀、抢购控库存
//取值,不存在则初始为0
long num = _cacheClient.StringIncrement("key", 0)
//判断,比如和缓存里的商品总库存比较
//计数增加
_cacheClient.StringIncrement("key", 2)
以上就是C#中如何使用redis的详细内容,更多关于C#使用redis的资料请关注得得之家其它相关文章!
本文标题为:C#中如何使用redis
- Oracle中for循环的使用方法 2023-07-04
- .NET CORE DI 依赖注入 2023-09-27
- WPF使用DrawingContext实现绘制刻度条 2023-07-04
- 如何使用C# 捕获进程输出 2023-03-10
- Unity3D实现渐变颜色效果 2023-01-16
- 在C# 8中如何使用默认接口方法详解 2023-03-29
- c# 模拟线性回归的示例 2023-03-14
- user32.dll 函数说明小结 2022-12-26
- Unity Shader实现模糊效果 2023-04-27
- C# 使用Aspose.Cells 导出Excel的步骤及问题记录 2023-05-16