openresty 缓存,



openresty 缓存

        

              

                               

永久缓存

      

永久缓存:除非手动删除,缓存一直有效,适用于不经常变更的数据(如静态页面等)

      

永久缓存配置

    location / {
        proxy_store on;                                 #开启永久缓存
        root   /usr/share/nginx/cache;                  #缓存存储目录,手动创建,权限与worker线程相同
        
        proxy_temp_path /usr/share/nginx/cache_temp;    #缓存临时存储目录,自动创建
        proxy_store_access user:rw group:rw all:r;      #缓存读写规则
 
        if (!-e $request_filename) {                    #如果缓存中没有,则从后端服务器中查询
           proxy_pass http://172.18.0.3:8080;
        }
    }

       

              

                               

临时缓存

      

临时缓存:缓存设置有效期,如果在有效时间内没被访问,缓存自动失效

         

**************

临时缓存指令

        

proxy_cache_path :设置临时缓存路径、空间大小、有效期等,在http模块中设置,其他模块会报错

# proxy_cache_path /usr/share/nginx/cache levels=1:2 keys_zone=cache_one:50m inactive=1m max_size=500m;

/usr/share/nginx/cache:临时缓存保存目录
levels=1:2:临时缓存分层目录,从url hash的尾部截取,
           最后一个字符为一级目录,向前2个字符为二级目录
keys_zone=cache_one:50m:缓存区的名称,内存大小为50m
inactive=1m:主动清空在1m内未使用的缓存
max_size=500m:磁盘空间大小为500m

          

常用指令

proxy_cache_key $host-$uri-$is_args-$args;    设置缓存的key
proxy_cache_convert_head on                   是否将head请求转换为get请求,on表示转换

proxy_cache_methods:缓存的http请求方法,如get、post等

proxy_pass http://172.18.0.2:8080             缓存丢失时,访问后端服务获取数据

proxy_cache_lock:是否设置缓存锁
proxy_cache_lock_timeout:缓存锁的过期时间

proxy_cache_use_stale:是否使用过期的数据,可设置多个值,
                       可选值:error、timeout、updating、http_500等
proxy_cache_background_update on:后台更新缓存,并返回过期的数据给客户端
                                 proxy_cache_use_stale需要设置为updating


proxy_cache_min_uses:同一url请求多少次之后,进行缓存,默认1次
proxy_cache_revalidate:缓存过期时,向后端验证缓存内容是否过期

proxy_no_cache:不将数据保存为缓存
* proxy_no_cache $arg_a $arg_b ==> 请求中参数有a或者b,且值不为空或者0,不缓存

proxy_cache_bypass:不使用nginx缓存,直接访问后端服务
* proxy_cache_bypass $cookie_a  ==> cookie中有名为a的cookie,直接去后端服务获取数据

        

$upstream_cache_status:请求的缓存使用状态

# add_header X-cache-status $upstream_cache_status; 
# 响应中添加请求头,标识请求的缓存使用状态
HIT:缓存命中
MISS:没有缓存,请求传送到后端
Expired:缓存过期,请求传送到后端
STALE:无法从后端获取数据,返回旧的数据(proxy_cache_use_stale命令设置)
BY_PASS:绕过缓存,直接去后端获取数据(proxy_cache_bypass命令设置)
REVALIDATED:验证缓存是否过期(proxy_cache_revalidate命令设置)

          

**************

临时缓存配置

      

nginx.conf:proxy_cache_path指令

user  nginx;
worker_processes  1;
 
error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;
 
 
events {
    worker_connections  1024;
}
 
 
http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;
 
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';
 
    access_log  /var/log/nginx/access.log  main;
 
    sendfile        on;
    #tcp_nopush     on;
 
    keepalive_timeout  65;
 
    #gzip  on;
 
    proxy_temp_path  /usr/share/nginx/cache_temp     # 缓存数据先写入临时目录,再保存到proxy_cache_path指定的目录
    proxy_cache_path /usr/share/nginx/cache levels=1:2 keys_zone=cache_one:50m inactive=1m max_size=500m;
    include /etc/nginx/conf.d/*.conf;
}
 

                    

default.conf

server {
    listen       80;
    server_name  localhost;
 
    add_header X-via $server_addr;                    #代理服务器的ip地址
    add_header X-cache-status $upstream_cache_status; #缓存状态
 
    location / {
        proxy_cache cache_one;                        #缓存区的名称
        proxy_cache_key $host-$uri-$is_args-$args;    #缓存key值,$host:主机名,$uri:请求地址,$is_args:是否含有参数,若有则为?,没有则为空,$args:参数,没有则为空
 
        proxy_cache_valid 200 10m;                    #缓存有效期,200为10m
        proxy_cache_valid 304 1m;                     #缓存有效期,304为1m
        proxy_cache_valid 301 302 1h;                 #缓存有效期,301、302为1h
        proxy_cache_valid any 1m;                     #缓存有效期,其余为1m
 
        proxy_temp_path /usr/share/nginx/cache_temp;  #临时缓存目录
 
        proxy_pass http://192.168.57.10:8080;         #代理应用
    }
 
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
 
}

          

               

                               

使用示例

      

**************

应用

       

                         

       

HelloController

@RestController
public class HelloController {

    @RequestMapping("/hello")
    public String hello(){
        System.out.println("瓜田李下");
        return "hello 瓜田李下";
    }
}

        

Dockerfile

from java:8

workdir /usr/local/jar
copy hello.jar app.jar

expose 8080
entrypoint ["java", "-jar", "app.jar"]

          

edit configuration ==> docker

               

       

 启动应用

               

               

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.7.1)

2022-07-03 07:21:06.803  INFO 1 --- [           main] com.example.demo.DemoApplication         : Starting DemoApplication v0.0.1-SNAPSHOT using Java 1.8.0_111 on 02ecd322ed90 with PID 1 (/usr/local/jar/app.jar started by root in /usr/local/jar)
2022-07-03 07:21:06.815  INFO 1 --- [           main] com.example.demo.DemoApplication         : No active profile set, falling back to 1 default profile: "default"
2022-07-03 07:21:09.366  INFO 1 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2022-07-03 07:21:09.394  INFO 1 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2022-07-03 07:21:09.395  INFO 1 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.64]
2022-07-03 07:21:09.638  INFO 1 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2022-07-03 07:21:09.638  INFO 1 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 2676 ms
2022-07-03 07:21:10.785  INFO 1 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2022-07-03 07:21:10.808  INFO 1 --- [           main] com.example.demo.DemoApplication         : Started DemoApplication in 5.211 seconds (JVM running for 6.557)
2022-07-03 07:23:30.262  INFO 1 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2022-07-03 07:23:30.263  INFO 1 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2022-07-03 07:23:30.265  INFO 1 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 2 ms

        

**************

openresty

       

nginx.conf

pcre_jit on;

events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;

    client_body_temp_path /var/run/openresty/nginx-client-body;
    proxy_temp_path       /var/run/openresty/nginx-proxy;
    fastcgi_temp_path     /var/run/openresty/nginx-fastcgi;
    uwsgi_temp_path       /var/run/openresty/nginx-uwsgi;
    scgi_temp_path        /var/run/openresty/nginx-scgi;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    proxy_cache_path /usr/share/nginx/cache levels=1:2 keys_zone=cache_one:50m inactive=1m max_size=500m;
                     # 需要先创建缓存目录:/usr/share/nginx/cache
    include /etc/nginx/conf.d/*.conf;
}

            

default.conf

server {
    listen       80;
    server_name  localhost;
 
    add_header X-via $server_addr;                    #代理服务器的ip地址
    add_header X-cache-status $upstream_cache_status; #缓存状态
 
    location / {
        proxy_cache cache_one;                        #缓存区的名称
        proxy_cache_key $host-$uri-$is_args-$args;    #缓存key值,$host:主机名,$uri:请求地址,$is_args:是否含有参数,若有则为?,没有则为空,$args:参数,没有则为空
 
        proxy_cache_valid 200 10m;                    #缓存有效期,200为10m
        proxy_cache_valid 304 1m;                     #缓存有效期,304为1m
        proxy_cache_valid 301 302 1h;                 #缓存有效期,301、302为1h
        proxy_cache_valid any 1m;                     #缓存有效期,其余为1m
 
        proxy_temp_path /usr/share/nginx/cache_temp;  #临时缓存目录
 
        proxy_pass http://172.18.0.3:8080;         #代理应用
    }
 
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
 
}

        

创建容器

docker run -it -d --net fixed --ip 172.18.0.12 -p 8000:80 \
-v /Users/huli/lua/openresty/conf6/cache:/usr/share/nginx/cache \
-v /Users/huli/lua/openresty/conf6/nginx.conf:/usr/local/openresty/nginx/conf/nginx.conf \
-v /Users/huli/lua/openresty/conf6/default.conf:/etc/nginx/conf.d/default.conf \
--name openresty6 lihu12344/openresty

           

使用测试

# 调用接口
huli@hudeMacBook-Pro conf6 % curl localhost:8000/hello
hello 瓜田李下%                                                                 

# 查看缓存
huli@hudeMacBook-Pro conf6 % ls cache
5

huli@hudeMacBook-Pro conf6 % ls cache/5
7e

huli@hudeMacBook-Pro conf6 % ls cache/5/7e
5223a0e758429d71efb8d04f348527e5

huli@hudeMacBook-Pro conf6 % cat cache/5/7e/5223a0e758429d71efb8d04f348527e5
?H?b?????????F?b???Ji?
KEY: localhost-/hello--
HTTP/1.1 200 
Content-Type: text/plain;charset=UTF-8
Content-Length: 18
Date: Sun, 03 Jul 2022 07:34:34 GMT
Connection: close

hello 瓜田李下                                                                 

       

             

相关内容