Last active
August 29, 2015 14:15
-
-
Save jonocairns/da2e39ae047f7de894dc to your computer and use it in GitHub Desktop.
Cache wrapper for redis which will try get a value from the cache - if it doesn't exist it will perform the method you supply and set that as the cache value
This file contains 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
//cache | |
public async Task<T> TryGet<T>(string key, Func<Task<T>> ifCacheMissAction) | |
{ | |
if (ifCacheMissAction == null) throw new ArgumentNullException("ifCacheMissAction"); | |
if (string.IsNullOrEmpty(key)) throw new ArgumentNullException("key"); | |
if (_isEnabled) | |
{ | |
RedisValue redisValue = Cache.StringGet(key); | |
// the following is a bit yolo | |
if (redisValue.HasValue && redisValue != "{}") | |
{ | |
return JsonConvert.DeserializeObject<T>(redisValue); | |
} | |
} | |
T item = await ifCacheMissAction(); | |
SetValue(key, item); | |
return item; | |
} | |
//usage | |
public async Task<IEnumerable<AgendaItem>> Retrieve() | |
{ | |
const string resource = "program/agenda"; | |
const string cacheKey = "RetrieveAgenda"; | |
IEnumerable<AgendaItem> agendaItems = await _redisCache.TryGetList(cacheKey, async () => | |
{ | |
RestRequest restRequest = new RestRequest(resource, Method.GET); | |
IEnumerable<AgendaItemDto> agendaItemDtos = | |
await | |
_integrationClient.ExecuteGetRequest<IEnumerable<AgendaItemDto>>(restRequest, | |
"There was an issue hitting the endpoint: {0}".FormatWith(resource)); | |
return AgendaMapper.MapMany(agendaItemDtos); | |
}); | |
return agendaItems; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment