c# - 如何使用 .NET enyim 增加 memcached 值?

标签 c# .net memcached enyim enyim.caching

互联网上似乎缺乏有关 Enyim Increment 方法的信息或文档。我不太明白它在做什么。文档指出:

 Increment(string key, ulong defaultValue, ulong delta);

"Increments the value of the specified key by the given amount. Operation happens atomically on the server."

如果我能让它发挥作用,这听起来一切都很好。

虽然没有人有很多明确的答案,但共识似乎是,如果 memcached 中不存在 key ,该方法应该将该值设置为给定的默认值。但是,我一生都无法获得一个 key 来存储默认值。

我不想使用(存储+增量)组合,因为它需要在多服务器架构中使用,并且我无法保证操作是原子的。

关于如何成功增加 memcached 键的值有什么想法或指示吗?一个 super 好处是默认值也有一个生存时间。

编辑:我已经在“文本”和“二进制”协议(protocol)中尝试过此操作,但似乎无法让它在任一设置中设置默认值。

预先感谢您的帮助!

最佳答案

这篇文章可能有点旧,但这里是使用 Enyim memcacheD 处理增量命令的代码片段。

        client.Store(StoreMode.Set, "mykey", "5");

        var incrementedValue = client.Increment("mykey", 2, 1);

在上面的示例中,键 mykey 的初始值已设置为 5。请注意,该值必须是字符串格式的整数(“5”而不是 5) .

第二行会将值增加 1。如果键不存在,则将值设置为 2,而不增加它。

以下代码片段使用 TTL 重载。

            //initial set, considering that the key did not exist before, the value will be 5
            //and it will be valid for 6 seconds
            var initialValue = client.Increment("mykey", 5, 1, TimeSpan.FromSeconds(6));
            Console.WriteLine(initialValue); //5
            //this will increament the value by 1, keeps it in cache for 10 seconds
            var incremented = client.Increment("mykey", 5, 1, TimeSpan.FromSeconds(10));
            var cachedData = client.Get("mykey");
            Console.WriteLine(cachedData); //6
            Thread.Sleep(11*1000);
            var cachedData_afterExpiry = client.Get("mykey");
            Console.WriteLine(cachedData_afterExpiry??"NULL");//this should be null 

关于c# - 如何使用 .NET enyim 增加 memcached 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25249570/

相关文章:

c# - RavenDB,使用嵌入式数据库存储数据的唯一方法是在 'system database' 中?

c# - 在 Npgsql 中获取数据库列表

c# - 使用 FluentNHibernate NHibernate 3.3 的错误映射

c# - 使用 linq 时从 WCF 服务返回什么?

c# - 如何在 C# 中将数据从指针复制到指针?

c - C 中 MemCached 的示例代码

php - Memcached 无法在 PHP 中运行

c# - <url> 的前缀 “cannot be redefined from ” 在同一个开始元素标签内

ruby-on-rails-3 - Rails 缓存操作不会过期

c# - Rhino Mock 与 Debug模式?