2

我目前正在使用服务堆栈 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;
}

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

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

域实体 => json => 解压缩 => 域实体。

似乎浪费了很多精力。

任何示例代码或指向 ToOptimizedResultUsingCache 更好解释的指针将不胜感激。

4

1 回答 1

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);

如果你想全局压缩,你可以关注这篇文章: 启用 gzip/deflate 压缩

希望这是有道理的。

俄罗斯

于 2013-09-30T22:43:24.403 回答