1.前言
雖然客戶端緩存效果很好,但它有一個核心問題:要在本地提供資源,必須先將其存儲在緩存中。因此,每個客戶端都需要其緩存的資源。如果請求的資源需要大量計算,則無法擴展。服務器端緩存背后的理念是計算一次資源,然后從緩存中將其提供給所有客戶端。
專用的服務器端資源緩存解決方案: Memcached,Varnish,Squid、Redis、Hazelcast。
2.演示
使用 Apache APISIX 來演示服務器端緩存。APISIX 依賴于代理緩存插件進行緩存。不幸的是,目前 APISIX 不與任何第三方緩存解決方案集成。它提供兩種選項:基于內存和基于磁盤。
一般來說,前者速度更快,但內存昂貴,而后者速度較慢,但??磁盤存儲便宜。然而,在 OpenResty 中,由于 LuaJIT 處理內存的方式,磁盤選項可能更快。您可能應該從磁盤開始,如果速度不夠快,請掛載/dev/shm。
2.1.創建新路由
apisix.yaml配置:
routes:- uri: /cacheupstream_id: 1plugins:proxy-rewrite:regex_uri: ["/cache(.*)", "/$1"]proxy-cache: ~
請注意,默認緩存鍵是主機和請求 URI,其中包括查詢參數。
當然也可以通過修改路由配置繞過緩存,配置如下:
routes:- uri: /cache*upstream_id: 1proxy-cache:cache_bypass: ["$arg_bypass"]
curl -v localhost:9080/cache?bypass=please
2.2.默認proxy-cache配置
使用默認的基于磁盤的配置。
config-default.yaml配置:
proxy_cache: # Proxy Caching configurationcache_ttl: 10s # The default caching time in disk if the upstream does not specify the cache timezones: # The parameters of a cache- name: disk_cache_one # The name of the cache, administrator can specify# which cache to use by name in the admin api (disk|memory)memory_size: 50m # The size of shared memory, it's used to store the cache index for# disk strategy, store cache content for memory strategy (disk|memory)disk_size: 1G # The size of disk, it's used to store the cache data (disk)disk_path: /tmp/disk_cache_one # The path to store the cache data (disk)cache_levels: 1:2 # The hierarchy levels of a cache (disk)- name: memory_cachememory_size: 50m
啟動對應的應用,即可進行后續的測試工作。
2.3.測試
2.3.1.測試命令
curl -v localhost:9080/cache
< HTTP/1.1 200 OK
< Content-Type: text/html; charset=utf-8
< Content-Length: 147
< Connection: keep-alive
< Date: Thu, 16 May 2024 06:35:00 GMT
< Last-Modified: Thu, 16 May 2024 07:41:00 GMT
< ETag: "637e271f-93"
< Server: APISIX/3.0.0
< Apisix-Cache-Status: MISS
< Accept-Ranges: bytes
2.3.2.MISS
.
.
.
Apisix-Cache-Status: MISS
.
.
.
2.3.3.HIT
如果我們curl再次在默認緩存過期時間(300 秒)之前,響應來自緩存
.
.
.
Apisix-Cache-Status: HIT
.
.
.
2.3.4.EXPIRED
.
.
.
Apisix-Cache-Status: EXPIRED
.
.
.
2.3.5.清除整個緩存
請注意,我們可以使用自定義 PURGE HTTP 方法顯式清除整個緩存:
curl localhost:9080/cache -X PURGE