How can I Increment a memcached value with .NET enyim?

1.2k Views Asked by At

The internet seems to be fairly void of information or documentation about the Enyim Increment method. I cant quite figure out what it is doing. The documentation states:

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

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

This sounds all well and good if I could get it to work.

Though nobody has many clear answers, the consensus seems to be that the method is supposed to set the value to the given default value, should the key not exist in memcached. However, I cant for the life of me get a key to store to a default value.

I don't want to use a (store + increment) combo because it needs to be used across a multi-server architecture and I could not guarantee the operation would be atomic.

Any ideas or pointers on how to successfully increment the value of a memcached key? A super bonus would be to also have the default value have a time to live as well.

Edit: I have tried this in both the "Text" and "Binary" protocols and cant seem to get it to set a default value in either setting.

Thanks in advance for the help!

1

There are 1 best solutions below

2
On BEST ANSWER

This post might be a bit old, but here is the code snippet to handle the Increment command using Enyim memcacheD.

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

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

In the above example, the initial value of the key, mykey, has been set to 5. Please note that the value must be an integer in a string format ( "5" not 5 ).

The second line will increment the value by 1. If the key does not exist, it sets the value to 2 without incrementing it.

The following snippet uses the TTL overload.

            //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