2013-09-30 49 views
2

我目前使用服務堆棧ICacheClient緩存內存。使用服務堆棧緩存數據聚合ToOptimizedResultUsingCache

注意:下面的代碼是一些僞代碼,因爲我需要刪除客戶特定的名稱。

可以說我有以下彙總:

博文 =>評論

我想這樣做以下:

// So I need to go get the blogPost and cache it: 
var blogPostExpiration = new TimeSpan(0, 0, 30); 
var blogPostCacheKey = GenerateUniqueCacheKey<BlogPostRequest>(request); 
blogPostResponse = base.RequestContext.ToOptimizedResultUsingCache<BlogPostResponse>(base.CacheClient, blogPostCacheKey, blogPostExpiration,() => 
        _client.Execute((request))); 

// Then, annoyingly I need to decompress it to json to get the response back into my domain entity structure: BlogPostResponse 
string blogJson = StreamExtensions.Decompress(((CompressedResult)blogPostResponse).Contents, CompressionTypes.Default); 
response = ServiceStack.Text.StringExtensions.FromJson<BlogPostResponse>(blogJson); 

// Then I do the same so get the comments: 
var commentsExpiration = new TimeSpan(0, 0, 30); 
var commentsCacheKey = GenerateUniqueCacheKey<CommentsRequest>(request); 
var commentsResponse = base.RequestContext.ToOptimizedResultUsingCache<CommentsResponse>(base.CacheClient, commentsCacheKey, commentsExpiration,() => 
        _client.Execute((request))); 

// And decompress again as above 
string commentsJson = StreamExtensions.Decompress(((CompressedResult)commentsResponse).Contents, CompressionTypes.Default); 
var commentsResponse = ServiceStack.Text.StringExtensions.FromJson<CommentsResponse>(commentsJson); 

// The reason for the decompression becomes clear here as I need to attach my Comments only my domain emtity. 
if (commentsResponse != null && commentsResponse.Comments != null) 
{ 
    response.Comments = commentsResponse.Comments; 
} 

我想知道的是,有一個較短的辦法做如下:

獲取我的數據並緩存它,讓它回到我的域實體格式,而不必寫上述所有行s的代碼。我不想經歷以下痛苦!:

Domain entity => json => decompress => domain entity。

看起來像很多浪費的能量。

任何示例代碼或指針更好地解釋ToOptimizedResultUsingCache將不勝感激。

回答

4

好吧,我即將回答我自己的問題。看起來像ToOptimizedResult和ToOptimizedResultUsingCache這樣的方法(擴展方法)可以讓你像壓縮和緩存一樣免費。

但是,如果你想要更多的控制,你只需要使用緩存,你通常會:

// Generate cache key 
var applesCacheKey = GenerateUniqueCacheKey<ApplesRequest>(request); 

// attempt to get match details from cache 
applesResponse = CacheClient.Get<ApplesDetailResponse>(applesDetailCacheKey); 

// if there was nothing in cache then 
if (applesResponse == null) 
{ 
    // Get data from storage 
    applesResponse = _client.Execute(request); 

    // Add the data to cache 
    CacheClient.Add(applesCacheKey, applesResponse, applesExpiration); 
} 

後你建立你聚集,放入高速緩存可以壓縮整個事情:

return base.RequestContext.ToOptimizedResult(applesResponse); 

如果要壓縮在全球範圍你可以按照這個帖子: Enable gzip/deflate compression

希望這是有道理的。

RuSs