public void Set(ICacheId cacheId, object toCache) { _memoryCache.Set(CreateCacheKey(cacheId), toCache, new MemoryCacheEntryOptions { Size = 1, AbsoluteExpirationRelativeToNow = _duration }); }
private async Task <TResponse> RequestAsync <TResponse>(object request, string traceSpanId, string traceId) { //get from cache ICacheId cacheId = request as ICacheId; if (cacheId != null) { TResponse cached = _cacheHandler.Get <TResponse>(cacheId); if (cached != null && !cached.Equals(default(TResponse))) { return(cached); } } //message direction string directory = request.GetType().GetCustomAttribute <BusNamespace>().Directory; string subdirectory = request.GetType().GetCustomAttribute <BusNamespace>().Subdirectory; string exchange = "request_" + directory.ToLower() + "_" + subdirectory.ToLower(); string routingKey = request.GetType().Name.ToLower(); //correlation string correlationId = Guid.NewGuid().ToString(); //sending request await Task.Factory.StartNew(() => { _requestChannel.ExchangeDeclare(exchange, ExchangeType.Direct, true, false); _responseQueue.AddGroup(correlationId); IBasicProperties properties = _requestChannel.CreateBasicProperties(); properties.MessageId = Guid.NewGuid().ToString(); properties.AppId = _appId; properties.ReplyTo = DIRECT_REPLY_QUEUE; properties.CorrelationId = correlationId; properties.Headers = new Dictionary <string, object>(); properties.Headers.Add("TraceSpanId", traceSpanId); properties.Headers.Add("TraceId", traceId); properties.Persistent = false; _requestChannel.BasicPublish(exchange, routingKey, properties, Encoding.UTF8.GetBytes(_jsonConverter.Serialize(request))); }, _cancellationTokenSource.Token, TaskCreationOptions.DenyChildAttach, _sendTaskScheduler); //response object ResponseWrapper <TResponse> responseWrapper = null; //waiting response await Task.Factory.StartNew(() => { string messageBody = _responseQueue.WaitMessage(correlationId); if (messageBody != null) { responseWrapper = _jsonConverter.Deserialize <ResponseWrapper <TResponse> >(messageBody); } _responseQueue.RemoveGroup(correlationId); }, _cancellationTokenSource.Token, TaskCreationOptions.DenyChildAttach, _receiveTaskScheduler); //timeout if (responseWrapper == null) { throw new TimeoutException(request.GetType().Name + " did not respond"); } //remote error if (responseWrapper.ExceptionCode != null) { throw new RemoteException(responseWrapper.ExceptionCode, responseWrapper.ExceptionMessage); } //add to cache if (cacheId != null) { _cacheHandler.Set(cacheId, responseWrapper.Response); } //response return(responseWrapper.Response); }
private string CreateCacheKey(ICacheId cacheId) { return(cacheId.GetType().FullName + "-" + cacheId.CreateCacheSuffix()); }
public TCached Get <TCached>(ICacheId cacheId) { return(_memoryCache.Get <TCached>(CreateCacheKey(cacheId))); }