C# .NET: Simple Enyim Setup to Use .NET to Connect to Memcached Server

6/5/2014 9:28:35 PM

Enyim is a .NET wrapper for connecting to a Memcached server. Download the Enyim package from Nuget (EnyimMemcached)

<!-- Web.config -->
<configuration>
	<configSections>

		<sectionGroup name="enyim.com">
			<section name="memcached" type="Enyim.Caching.Configuration.MemcachedClientSection, Enyim.Caching" />
			<!-- for logging, not required -->
			<!--<section name="log" type="Enyim.Caching.Configuration.LoggerSection, Enyim.Caching" />-->
		</sectionGroup>   

	</configSections>
	
	...
	
	<!-- child of configuration -->
	<enyim.com>
		<!-- for logging, not required, EnyimMemcached-log4net and log4net Nuget packages required for logging -->
		<!--<log factory="Enyim.Caching.Log4NetFactory, Enyim.Caching.Log4NetAdapter" />-->
		<memcached protocol="Binary">
			<servers>
				<!-- make sure you use the same ordering of nodes in every configuration you have -->
				<add address="my-memcacheserver-at-aws.compute-1.amazonaws.com" port="11211" />        
			</servers>			
		</memcached>        
	</enyim.com>
</configuration>


//C#
//create client
Enyim.Caching.MemcachedClient memCache = new Enyim.Caching.MemcachedClient();

//this object must be marked as serializable
var myObj = new MyObj();

//a unique key is required. I am assuming myObj has an Id field that is unique
string cacheKey = "myObj_" + myObj.Id;

//store object
int secondsToCache = 60;
memCache.Store(Enyim.Caching.Memcached.StoreMode.Set, cacheKey, myObj, DateTime.Now.AddSeconds(secondsToCache));

//get object
object getMyObj1 = memCache.Get(cacheKey);
//or
MyObj getMyObj2 = <MyObj>memCache.Get(cacheKey);