缓存之路

本文转载自:

原文链接: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);
	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章