偶然發(fā)現(xiàn),本站的阿里云服務(wù)器上運(yùn)行著一個(gè)叫 nscd 的服務(wù)。搜索了一番,得知 nscd(Name Service Cache Daemon)是一種能夠緩存 passwd、group、hosts 的本地緩存服務(wù),分別對應(yīng)三個(gè)源 /etc/passwd、/etc/hosts、/etc/resolv.conf。其最為明顯的作用就是加快 DNS 解析速度,在接口調(diào)用頻繁的內(nèi)網(wǎng)環(huán)境建議開啟。
這里利用 nscd 的 hosts 緩存服務(wù)來實(shí)現(xiàn) linux 下的 dns 緩存。
安裝
$ yum install nscd
安裝后,nscd 的緩存文件路徑為/var/db/nscd/。
配置
nscd 的配置文件默認(rèn)路徑為/etc/nscd.conf。
阿里云主機(jī)的 nscd 配置信息如下:
# 日志文件
#logfile /var/log/nscd.log
# 調(diào)試級別
debug-level 5
# 等待請求的線程數(shù)
threads 6
# 最大線程數(shù)
max-threads 128
# 運(yùn)行用戶
server-user nscd
paranoia no
# 禁用passwd緩存
enable-cache passwd no
# 禁用group緩存
enable-cache group no
# 啟用hosts緩存
enable-cache hosts yes
# 指定緩存命中項(xiàng)的TTL,單位為s
positive-time-to-live hosts 5
# 指定緩存未命中項(xiàng)的TTL,單位為s
negative-time-to-live hosts 20
# 散列表大小
suggested-size hosts 211
# 啟用hosts文件的修改情況檢查
check-files hosts yes
persistent hosts yes
shared hosts yes
# 最大緩存庫大小
max-db-size hosts 33554432
命令
nscd 服務(wù)默認(rèn)是關(guān)閉的,通過service nscd start開啟。
- 查看統(tǒng)計(jì)信息
$ nscd -g
nscd configuration:
5 server debug level
59d 17h 15m 50s server runtime
6 current number of threads
128 maximum number of threads
0 number of times clients had to wait
no paranoia mode enabled
3600 restart internal
5 reload count
hosts cache:
yes cache is enabled
yes cache is persistent
yes cache is shared
211 suggested size
216064 total data pool size
0 used data pool size
5 seconds time to live for positive entries
20 seconds time to live for negative entries
0 cache hits on positive entries
0 cache hits on negative entries
41794 cache misses on positive entries
42276 cache misses on negative entries
0% cache hit rate
0 current number of cached values
365 maximum number of cached values
8 maximum chain length searched
0 number of delays on rdlock
0 number of delays on wrlock
0 memory allocations failed
yes check /etc/hosts for changes
- 清除緩存
# 當(dāng)更改完域名指向后,清除dns緩存
$ nscd -i hosts
- 關(guān)閉服務(wù)
$ nscd -K
作用
開啟 nscd 的 hosts 緩存服務(wù)后,每次內(nèi)部接口請求不會(huì)都發(fā)起 dns 解析請求,而是直接命中 nscd 緩存散列表,從而獲取對應(yīng)服務(wù)器 ip 地址,這樣可以在大量內(nèi)部接口請求時(shí)減少接口的響應(yīng)時(shí)間。