5.4 Cache Performance 缓存性能

Problem

You need to increase performance by caching on the client side.

问题

需要在客户端提升服务性能


Solution

Use client-side cache control headers:

location ~* .(css|js)$ {
    expires 1y;

    add\_header Cache-Control "public";
}

This location block specifies that the client can cache the content of

CSS and JavaScript files. The expires directive instructs the client

that their cached resource will no longer be valid after one year. The

add_header directive adds the HTTP response header CacheControl to the response, with a value of public, which allows any

caching server along the way to cache the resource. If we specify pri‐

vate, only the client is allowed to cache the value.

解决方案

使用客户端缓存控制消息头:

location ~* .(css|js)$ {
    expires 1y;

    add\_header Cache-Control "public";
}

该 location 块指令设置成功后,客户端可以对 CSS 和 JS 文件进行缓存。expires

指令将所有缓存的有效期设置为 1 年。add_header 指令将 HTTP 消息头 Cache-Control

设置成 public 并加入响应中,表示所有的缓存服务器都可以缓存资源。如果将它的值

设置为 private,则表示仅允许客户端对资源进行缓存。


Discussion

Cache performance has to do with many variables, disk speed being

high on the list. There are many things within the NGINX configu‐

ration you can do to assist with cache performance. One option is to

set headers of the response in such a way that the client actually

caches the response and does not make the request to NGINX at all,

but simply serves it from its own cache.

结论

缓存的性能和许多因素有关,其中磁盘读写速度是影响缓存性能的重要原因之一。

在 NGINX 配置指令中,还有很多能够提升性能的指令。像上例中配置的,通过

设置 Cache-Control 响应消息头,客户端会直接从本地读取缓存,而不会将请求

发送给服务器来提升性能。

results matching ""

    No results matching ""