Skip to content

Instantly share code, notes, and snippets.

@davybrion
Created September 15, 2012 16:12
Show Gist options
  • Save davybrion/3728632 to your computer and use it in GitHub Desktop.
Save davybrion/3728632 to your computer and use it in GitHub Desktop.
code snippets for "Using Distributed Caching With Agatha" post
public class MembaseCache : ICache
{
private readonly MembaseClient membaseClient;
public MembaseCache(string region = null)
{
// this implementation assumes password-less buckets
membaseClient = new MembaseClient(region, null);
}
public Response GetCachedResponseFor(Request request)
{
return membaseClient.Get<Response>(GetKey(request));
}
public void Store(Request request, Response response, TimeSpan expiration)
{
membaseClient.Store(StoreMode.Set, GetKey(request), response, expiration);
}
public void Clear()
{
membaseClient.FlushAll();
}
private static string GetKey(Request request)
{
return string.Format("{0}_{1}", request.GetType().FullName, request.GetHashCode());
}
}
public class MembaseCacheProvider : ICacheProvider
{
public ICache BuildCache(string region)
{
return new MembaseCache(region);
}
}
public class MembaseTranscoder : ITranscoder
{
public CacheItem Serialize(object o)
{
using (var stream = new MemoryStream())
{
var serializer = new DataContractSerializer(typeof(Response), KnownTypeProvider.GetKnownTypes(null));
serializer.WriteObject(stream, o);
var data = stream.ToArray();
return new CacheItem(((ushort)(((ushort)Type.GetTypeCode(o.GetType())) | 0x100)),
new ArraySegment<byte>(data, 0, data.Length));
}
}
public object Deserialize(CacheItem item)
{
using (var stream = new MemoryStream(item.Data.Array.Skip(item.Data.Offset).ToArray()))
{
var serializer = new DataContractSerializer(typeof(Response), KnownTypeProvider.GetKnownTypes(null));
return serializer.ReadObject(stream);
}
}
}
<membase>
<servers bucket="_defaultRegion">
<add uri="http://localhost:8091/pools/default" />
</servers>
<transcoder type="Agatha.Common.Caching.MembaseTranscoder, Agatha.Common" />
</membase>
var config = new ServiceLayerConfiguration(Assembly.GetExecutingAssembly(),
typeof(HelloWorldRequest).Assembly, typeof(Agatha.Castle.Container))
{
CacheProviderImplementation = typeof(MembaseCacheProvider)
};
config.Initialize();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment