地方エンジニアの学習日記

興味ある技術の雑なメモだったりを書いてくブログ。たまに日記とガジェット紹介。

nginx open_file_cacheで静的ファイルのcache

open_file_cacheを利用するとファイルディスクリプタやサイズ、更新時間といった情報をキャッシュすることができる。

設定例

    open_file_cache max=200000 inactive=20s;
    open_file_cache_valid 30s;
    open_file_cache_min_uses 2;
    open_file_cache_errors on;

キャッシュがいっぱいになったあとはLRUで削除されていく。

あくまでもfileをopenした段階でのメタデータのキャッシュなのでファイル自体がキャッシュされるわけではない。

(openした情報をキャッシュしておくことでopen(2)なりstat(2)などを発行しなくなる)

キャッシュの構造体あたりを見てるとbtreeって言ってるのでキャッシュの探索自体は平衡探索木なのだろうか。(ソース未確認)

struct ngx_cached_open_file_s {
    ngx_rbtree_node_t        node;
    ngx_queue_t              queue;

    u_char                  *name;
    time_t                   created;
    time_t                   accessed;

    ngx_fd_t                 fd;
    ngx_file_uniq_t          uniq;
    time_t                   mtime;
    off_t                    size;
    ngx_err_t                err;

    uint32_t                 uses;

#if (NGX_HAVE_OPENAT)
    size_t                   disable_symlinks_from;
    unsigned                 disable_symlinks:2;
#endif

    unsigned                 count:24;
    unsigned                 close:1;
    unsigned                 use_event:1;

    unsigned                 is_dir:1;
    unsigned                 is_file:1;
    unsigned                 is_link:1;
    unsigned                 is_exec:1;
    unsigned                 is_directio:1;

    ngx_event_t             *event;
};

ファイルアクセス自体はこの辺でやってる。結構シンプル

https://github.com/nginx/nginx/blob/master/src/core/ngx_open_file_cache.c#L840

あくまでもキャッシュ対象はメタデータのみなので大量の静的ファイルを扱うサーバであればキャッシュの効果がとてもありそう。

ただユーザサイドではなくサーバ側でどうしてもキャッシュが必要な際にこれを頼ってベンチマークとってみても思ったより効果薄ってオチは結構ありそう。。

nginx.org