使用Service堆栈ToOptimizedResultUsingCache缓存数据聚合

时间:2013-09-30 00:55:03

标签: caching servicestack

我目前正在使用Service stack ICacheClient来缓存内存。

注意:下面的代码是我需要删除客户特定名称的伪代码。

假设我有以下聚合:

博文 =>评论

我想这样做:

// 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;
}

我想知道的是有更短的方式来执行以下操作:

获取我的数据并对其进行缓存,将其恢复为我的域实体格式,而无需编写上述所有代码行。我不想经历以下痛苦!:

域实体=&gt; json =&gt; decompress =&gt;域实体。

似乎浪费了很多精力。

非常感谢任何示例代码或更好地解释ToOptimizedResultUsingCache的指示。

1 个答案:

答案 0 :(得分: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

希望这是有道理的。

拉​​斯