DNS(二)之构建域名解析缓存

时间:2024-04-22 08:23:05

域名解析缓存的必要性

在部署服务的时候,很多程序需要使用域名解析的功能,一般配置/etc/resovl.conf去指定DNS服务器的IP,但是如果程序发起的请求量较大,那么服务器就容易被DNS服务器禁止访问(至于为什么会被禁止,你懂得),同事每次去外网请求DNS解析的话,时延也特别大,乃至发生请求超时的情况,这个是,我们就要配置一个透明的DNS解析缓存服务器,达到的效果如下:

  1. 优化DNS响应速度 通过缓存DNS的请求结果,后续相同的DNS请求不需要在访问公网的DNS请求便可获得结果,减少了网络访问的延时。
  2. 减少DNS服务器对公网的依赖 在缓存周期内,相同的DNS请求不再发生到外网的网络通信行为,可以减少短暂的外部网络不可用导致的影响
NSCD安装配置方法

NSCD(Name server caching Daemon 名称服务缓存进程)不需要对应用程序或者解析器做任何修改,/etc/resovl.conf 也不需要做任何变化,对于系统部署的影响最小。因此NSCD成为linux环境最为广泛的域名缓存软件,本次使用该软件作为域名缓存服务,在CentOS6.6上,安装NSCD的方法比较简单,使用yum安装即可,命令如下:

[root@localhost ~]# yum -y install nscd
[root@localhost ~]# ls /etc/nscd.conf
/etc/nscd.conf #nscd的配置文件

我们看看配置文件,我们主要关心下面这几段,yum安装好后在63行-70行:

 63         enable-cache            hosts           yes
64 positive-time-to-live hosts 3600
65 negative-time-to-live hosts 20
66 suggested-size hosts 211
67 check-files hosts yes
68 persistent hosts yes
69 shared hosts yes
70 max-db-size hosts 33554432

参数解释

  • enable-cache 指定对DNS解析进行缓存
  • positive-time-to-live 对解析成功的DNS结果进行缓存时间
  • negative-time-to-live 指对解析成功的DNS结果进行缓存的时间,例如网络故障导致DNS解析失败或者请求的DNS条目没有配置等
  • suggested-size 是NSCD内部哈希表的大小,如果缓存条目数量大于默认的211,如大于10倍,那么修改此值。
  • check-files 指是否检查/etc/hosts文件的变化
  • persistent 重启NSCD进程时是否保留已缓存的条目
  • shared 是否允许客户端直接查询NSCD的内存镜像以获得结果
  • max-db-size 是指DNS的缓存大小,以字节为单位

启动服务

[root@localhost store]# /etc/init.d/nscd start
验证域名缓存
[root@localhost store]# nscd -g
'''''
hosts cache: yes cache is enabled
yes cache is persistent
yes cache is shared
211 suggested size
216064 total data pool size
520 used data pool size
3600 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
0 cache misses on positive entries
0 cache misses on negative entries
0% cache hit rate
0 current number of cached values
0 maximum number of cached values
0 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 [root@localhost ~]# wget -SO /dev/null http://www.baidu.com/ #换不同的域名多wget几次,就发现这数值上去了。 [root@localhost store]# nscd -g
'''''
hosts cache: yes cache is enabled
yes cache is persistent
yes cache is shared
211 suggested size
216064 total data pool size
520 used data pool size
3600 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
15 cache misses on positive entries
0 cache misses on negative entries
0% cache hit rate
3 current number of cached values
5 maximum number of cached values
0 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
[root@localhost ~]# nscd -i hosts # 清空hosts当前缓存条目的