26
2019.2
缓存原理
作者: POPASP
整页缓存原理是将网页第一次访问时生成html静态文件,第二次访问时则直接输出该html文件,程序不再往下执行,直到缓存过期。为了讲解方便,我们现举例说明。
控制器文件index.asp,代码如下:
```brush:vb
<%
Class Index
sub cache
that.d("cacheTime") = now()
that.display("")
end sub
End Class
%>
```
模板文件Tpl/Index/cache.html,内容仅为一行
```brush:html
{$cacheTime}
```
访问
```brush:html
http://serverName/index.asp?c=index&a=cache
```
并多次刷新,我们会发现得到的是当前时间,没有进行任何缓存。
现在,我们把控制器文件index.asp的代码修改如下:
```brush:vb
<%
Class Index
sub cache
if not that.isCached("") then
'需要缓存的数据都写到这个if判断里面
that.d("cacheTime") = now()
end if
that.display("")
end sub
End Class
%>
```
再次访问刚才的网址,并多次刷新页面,我们会发现,页面中显示的时间定格在一个时间上。这就是我们要讲的整页缓存技术,仔细看代码,我们会发现比以前的代码多了一个判断语句,该判断语句使用了that.isCached方法,代码的其他部分不变。正是加了这个方法,达到了页面缓存的目的,那么缓存的html文件在哪呢?在Runtime/Cache/Index_Cache.html。打开这个文件,可以看到缓存的时间。
缓存时间默认是一天,如果想修改缓存时间,可以配置TMPL_CACHE_LIFETIME。
如果我们想将缓存时间改为10天,可以这样来做。
```brush:vb
<%
Class Index
sub cache
POP_MVC.config("TMPL_CACHE_LIFETIME") = 10 * 86400
if not that.isCached("") then
'需要缓存的数据都写到这个if判断里面
that.d("cacheTime") = now()
end if
that.display("")
end sub
End Class
%>
```
如果想将所有想要缓存的页面都设置成相同的缓存时间,请直接修改配置文件。
```brush:vb
if not that.isCached("") then
'需要缓存的数据都写到这个if判断里面
end if
```
没有使用上面这样的判断缓存的语句,则不会进行缓存,所以POPASP的缓存技术在使用上非常方便,达到了设计上的最优。