很多的网站都有记数器,用来记录网站的访问量,这给网站管理员即时了解本网站的运行及访问情况提供了很多的方便。笔者研究过很多用asp编写的计数器程序,发现大部份都是在一个访客访问站点的时候就打文本文件或数据库,读取以前的计数值进行加1,然后再写入文件,若网站访问量很大,可能会对系统造成很大的负担,那么有没有优化的方法呢,笔者经过研究测试,答案是:有。
熟悉asp的朋友都知道,asp提供一个application属性用来保存服务器的一些公共变量,我们可以用这个变量来保存记数器的信息。
思路是先设定两个application变量,一个application(“totalcount”),用来保存记数值;另一个application(“lastwritetime”),用来保存上次把记数值保存到文件的时间。我们可以自己定义把计数值保存到文件的间隔时间,比如1小时、1天或者一个月。在有访客访网站的时候,让application(“totalcount”)进行加1,如果上次保存计数的时间与现在的时间差大于我们设定的保存时间间隔值,那么就把当前的计数值写入文件保存,这样就减少了程序的io操作,节约了系统的负担。
为了避免发生意外,如断电或者服务器停止反应需待重启等,我们可以设定保存时间间隔为2小时,这样即使发生意外,损失也不会太大。
例程如下:
<%
dim ofso 定义fso组件对象
dim ofile 定义读写文件对象
dim ncount 定义从文件中读取的记数值
dim sfilepath 定义计数器保存文件的路径
const iinterval=2 定义保存时间间隔为2小时
sfilepath=server.mappath("count/count.txt") 假设计数器文件在根目录下的count目录中,文件名为count.txt
if application("totalcount")=0 or application("totalcount")="" then
如果第一次运行网站,比如重启后,我们就需要从文件中读取出以前的计数值
set ofso=server.createobject("scripting.filesystemobject") 实例化文件操作对象ofso
if not ofso.fileexists(sfilepath) then
ofile=ofso.createtextfile(sfilepath,true) 如果文件不存在,则创建一个文
件
ofile.write("1") 写入当前的计数值"1"
ofile.close
application("totalcount")=1
else
set ofile = ofsot.opentextfile(sfilepath)
ncount=ofile.readline
application("totalcount")=clng(ncount)+1
ofile.close
end if
application("lastwritetime")= now 设置最后一次访问的时间为当前时间
else
application("totalcount")= application("totalcount")+1
if datediff("h", application("lastwritetime"),now)>iinterval then
如果当前时间与上次保存计数值的时间差大于设定的时间间隔,则把计数值重新写入文件
set ofso=server.createobject("scripting.filesystemobject") 实例化文件操作对象ofso
ofile=ofso.opentextfile(sfilepath,true) 打开文件
ofile.write(application("totalcount")) 写入当前的计数值
ofile.close
application("lastwritetime")= now 设置最后一次访问的时间为当前时间
end if
end if
response.write("欢迎光临本网站,你是访问本网站的第" & application("totalcount") & "位访客!")
%>
本例程在windows2000 iis5.0下通过。
