Created
September 28, 2017 16:35
-
-
Save fatagun/7c1feb4e2926d95646024a2d6db0e9ab to your computer and use it in GitHub Desktop.
CacheWrapper
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public interface ICache<T> where T : class | |
{ | |
void Put(object key, T value); | |
T Get(object key); | |
void Update(object key, T value); | |
} | |
public abstract class CacheBase<T> : ICache<T> where T : class | |
{ | |
#region Implementation of ICache<T> | |
public abstract void Put(object key, T value); | |
public abstract T Get(object key); | |
public abstract void Update(object key, T value); | |
#endregion | |
} | |
public class RedisCache<T> : CacheBase<T> where T : class | |
{ | |
private readonly RedisConnection _connection; | |
public RedisCache(RedisConnection redisConnection) | |
{ | |
_connection = redisConnection; | |
_connection.Open(); | |
} | |
#region Overrides of CacheBase<T> | |
public override async void Put(object key, T value) | |
{ | |
using (MemoryStream memoryStream = new MemoryStream()) | |
{ | |
Serializer.Serialize(memoryStream, value); | |
await _connection.Strings.Set(0, key.ToString(), memoryStream.GetBuffer()); | |
} | |
} | |
public override T Get(object key) | |
{ | |
var value = _connection.Strings.Get(0, key.ToString()); | |
_connection.Wait(value); | |
using (MemoryStream memoryStream = new MemoryStream(value.Result)) | |
{ | |
var cachedEntity = Serializer.Deserialize<T>(memoryStream); | |
return cachedEntity; | |
} | |
} | |
public override void Update(object key, T value) | |
{ | |
throw new NotImplementedException(); | |
} | |
public void Publish(object key, T value) | |
{ | |
using (MemoryStream memoryStream = new MemoryStream()) | |
{ | |
Serializer.Serialize(memoryStream, value); | |
_connection.Wait(_connection.Publish("first", memoryStream.GetBuffer())); | |
} | |
} | |
public void Subscribe() | |
{ | |
_connection.GetOpenSubscriberChannel(); | |
using(var s = _connection.GetOpenSubscriberChannel()) | |
{ | |
s.Subscribe("channel", (str, mes) => Console.WriteLine(mes)); | |
} | |
} | |
#endregion | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment