【问题标题】:Server side caching and client side caching in webapiwebapi中的服务器端缓存和客户端缓存
【发布时间】:2014-12-02 15:58:50
【问题描述】:

我必须在 asp.net web api 方法中实现缓存,因为我正在从第三方数据源访问数据并且调用第三方数据源的成本很高,而且数据每 24 小时才会更新一次。所以在 Strathweb 的帮助下.我已经实现了这样的缓存

    /// <summary>
    /// Returns the sorted list of movies
    /// </summary>
    /// <returns>Collection of Movies</returns>
    [CacheOutput(ClientTimeSpan = 86400, ServerTimeSpan =86400)]
    public IEnumerable<Movie> Get()
    {
        return repository.GetMovies().OrderBy(c => c.MovieId);
    }

/// <summary>
/// Returns a movie
/// </summary>
/// <param name="movie">movieId</param>
/// <returns>Movie</returns>
[CacheOutput(ClientTimeSpan = 86400, ServerTimeSpan = 86400)]
public Movie Get(int movieId)
{
        var movie = repository.GetMovieById(movieId);
        if (movie == null)
        {
            var httpResponseMessage = new HttpResponseMessage(HttpStatusCode.NotFound)
            {
                Content = new StringContent(string.Format("No movie with ID = {0}", movieId)),
                ReasonPhrase = "Movie ID Not Found"
            };
            throw new HttpResponseException(httpResponseMessage);
        }
        return movie;
}

但是在 Strathweb 中,我看到了两个属性,一个是 ClientTimeSpan,另一个是 ServerTimeSpan。我不确定何时使用 ClientTimeSpan 以及何时使用 ServerTimeSpan。最简单的说法是,我想了解何时使用服务器端缓存以及何时使用使用客户端缓存以及两者之间的差异。

【问题讨论】:

标签: asp.net asp.net-mvc caching asp.net-web-api asp.net-web-api2


【解决方案1】:

正如定义所说

ClientTimeSpan(对应CacheControl MaxAge HTTP头)

ServerTimeSpan(响应应该在服务器端缓存多长时间)

代码示例,带有解释。

//Cache for 100s on the server, inform the client that response is valid for 100s
[CacheOutput(ClientTimeSpan = 100, ServerTimeSpan = 100)]
public IEnumerable<string> Get()
{
    return new string[] { "value1", "value2" };
}


//Inform the client that response is valid for 50s. Force client to revalidate.
[CacheOutput(ClientTimeSpan = 50, MustRevalidate = true)]
public string Get(int id)
{
    return "value";
}

SOURCE

【讨论】:

  • 感谢 Arindam 帮助我在 2 天内解决了 2 个问题。
【解决方案2】:

客户端时间跨度

如果您希望允许客户端(通常是浏览器)在用户计算机上本地缓存您的数据,请使用客户端缓存。好处是客户端在缓存过期之前可能不会请求您的 API。另一方面,您不能使此缓存无效,因为它存储在客户端。将此缓存用于非动态/不经常更改的数据。

服务器时间跨度

将数据存储在您的服务器上。您可以轻松地使此缓存无效,但它需要一些资源(内存)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-04
    • 2012-08-09
    • 2022-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多