本文轉載自:
原文鏈接:https://blog.csdn.net/yin__ren/article/details/93650603
原文鏈接:https://www.cnblogs.com/lovelinux199075/p/9064431.html
多級緩存,即在整個系統架構的不同系統層級進行數據緩存,以提升訪問效率,這也是應用最廣的方案之一;
組件級緩存
使用redis或者memcahe做緩存
應用級緩存
使用nginx proxy_cache
upstream node1 {
server 127.0.0.1:8080;
}
proxy_cache_path /cache levels=1:2 keys_zone=cache:100m max_size=100g inactive=500m use_temp_path=off;
server {
listen 80;
server_name www.own.com;
index index.html;
location / {
proxy_pass http://node1 ;
proxy_cache cache;
proxy_cache_valid 200 304 12h;
proxy_cache_valid any 10m;
add_header Nginx-Cache "$upstream_cache_status";
proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
}
}
參數詳解:
proxy_cache_path /soft/cache levels=1:2 keys_zone=cache:10m max_size=10g inactive=60m use_temp_path=off;
#proxy_cache //存放緩存臨時文件
#levels //按照兩層目錄分級
#keys_zone //開闢空間名,10m:開闢空間大小,1m可存放8000key
#max_size //控制最大大小,超過後Nginx會啓用淘汰規則
#inactive //60分鐘沒有被訪問緩存會被清理
#use_temp_path //臨時文件,會影響性能,建議關閉
proxy_cache cache;
proxy_cache_valid 200 304 12h;
proxy_cache_valid any 10m;
add_header Nginx-Cache "$upstream_cache_status";
proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
#proxy_cache //開啓緩存
#proxy_cache_valid //狀態碼200|304的過期爲12h,其餘狀態碼10分鐘過期
#proxy_cache_key //緩存key
#add_header //增加頭信息,觀察客戶端respoce是否命中
#proxy_next_upstream //出現502-504或錯誤,會跳過此臺服務器訪問下一臺服務器
驗證
jvm級緩存:
使用 Guava Cache
實現
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>18.0</version>
</dependency>
public class CacheServiceImpl implements CacheService {
private Cache<String, Object> commonCache = null;
@PostConstruct
public void init(){
commonCache = CacheBuilder.newBuilder()
.initialCapacity(10) //初始容量
.maximumSize(100) //key 的最大容量,超容則使用 LRU 移除
.expireAfterWrite(60, TimeUnit.SECONDS)
.build();
}
@Override
public void setCommonCache(String key, Object value) {
commonCache.put(key,value);
}
@Override
public Object getCommonCache(String key) {
return commonCache.getIfPresent(key);
}
}