Using Memcached with .NET C#
In order to use Memcached with .NET C# you will need a .NET C# Memcached client. In the following sections, we will demonstrate the use of EnyimMemcached, a .NET client library for Memcached written in C#.
To install EnyimMemcached, run the following command in the Package Manager Console:
PM> Install-Package EnyimMemcached
Opening a Connection to Memcached Using EnyimMemcached
The following code creates a connection to Memcached using EnyimMemcached:
using Enyim.Caching; using Enyim.Caching.Configuration; using Enyim.Caching.Memcached; MemcachedClientConfiguration config = new MemcachedClientConfiguration(); config.Servers.Add(new IPEndPoint("hostname", port)); config.Protocol = MemcachedProtocol.Binary; config.Authentication.Type = typeof(PlainTextAuthenticator); config.Authentication.Parameters["userName"] = "username"; config.Authentication.Parameters["password"] = "password"; config.Authentication.Parameters["zone"] = ""; var mc = new MemcachedClient(config);
To adapt this example to your code, make sure that you replace the following values with those of your bucket:
- In line 6, the first argument to
IPEndPointshould be your bucket’s hostname or IP address
- In line 6, the second argument to
IPEndPointshould be your bucket’s port
- In line 9,
userNameshould be set with your bucket’s username
- In line 10,
passwordshould be set with your bucket’s password
Reading and Writing Data with EnyimMemcached
Once connected to Memcached, you can start reading and writing data. The following code snippet writes the value
bar to the Memcached key
foo, reads it back, and prints it:
///<summary> ///open a connection to Memcached ///</summary> ... mc.Store(StoreMode.Set, "foo", "bar"); var value = mc.Get("foo"); Console.WriteLine(value);
The output of the above code should be:
Redis Enterprise running Memcached buckets in a highly available and auto-scalable manner, with predictable top performance.
Redis Enterprise Software lets you install an enterprise grade Memcached cluster in your environment of choice, whether an on-premises data-center or your preferred cloud platform. It gives you full control of your data and configuration – no clustering or sharding knowledge required!
Memcached Cloud is a fully managed cloud service for hosting and running Memcached datasets in a highly available and scalable manner, with predictable and stable top performance. It provides a storage engine for standard Memcached, as well as in-memory replication and instant auto-failover within the same data center or across data centers. The service completely frees developers from dealing with nodes, clusters, scaling, data persistence issues or failure recovery.
For more information on using Redis Labs’ products and services with net-c please see the Howto page.