【背景】网站首页是由多个<!--#include virtual="/inc/small1.html?encode=utf-8"-->组成,为减少服务器SSI(server side include)的压力,新网站需要对首页作静态化,以满足用户访问的性能需求。
【实现】通过部署在服务器上的shell脚本,在服务器端定时访问服务器的内部首页路径,保存为html, 存储到web服务的首页路径下。
1)首页下载函数
indexSave.sh
#!/bin/bash
# parameter1=homeUrl;
# parameter2=targetDir;
# parameter3=workDir;
homeUrl=$1
targetDir=$2
workDir=$3
tempFile1=$workDir"index.txt"
tempFile2=$workDir"index.html"
flagText="</body>"
time=`date +"%Y-%m-%d %H:%M:%S"`
date=`date +%Y_%m_%d`
rm -rf ${tempFile1}
rm -rf ${tempFile2}
validCount=0 #define the valid flag count
a=(0,1,2,3,4,5,6) #define the check flag array
a[0]="<html>"
a[1]="</html>"
a[2]="<title>XXXXX</title>"
a[3]="<head>"
a[4]="</head>"
a[5]="<body>"
a[6]="</body>"
num=${#a[@]}
let minsize=30000
let maxsize=40000
wget --cache=off ${homeUrl} -O${tempFile1}
if [ -f ${tempFile1} ];then
echo "We have downloaded "${tempFile1}" from "${homeUrl} "[${time}]">>run$date.log
while read line
do
temp=$line
for var in ${a[@]};
do
aa=`echo $temp|grep $var|wc -l`
if [ $aa -gt 0 ];then
echo "We have checked Valid flag${validCount}:"$temp>>run$date.log
let validCount++
fi
done
bb=`echo $temp|grep $flagText|wc -l`
if [ $bb = 0 ]
then
echo ${temp} >> ${tempFile2}
else
#echo "contains flag "${flagText}" append staticTime "${time}>>run$date.log
temp='<span staticTime="'${time}'" style="display:none"></span>'${temp}
echo ${temp} >> ${tempFile2}
fi
done < ${tempFile1}
else
echo "Fetal Error,we haven't got the "${tempFile1}" from "${homeUrl} "[${time}]">>run$date.log
fi
s=$(du -b $tempFile2|awk '{print $1}')
echo "We have generated the final file "$tempFile2",file size is "$s" bytes">>run$date.log
if [ $s -gt $minsize -a $s -lt $maxsize ];
then
echo "We have checked the final file size in bytes,it is between $minSize and $maxSize">>run$date.log
if [ $validCount -eq $num ];then
echo "We have checked all valid flags, total "$validCount" items">>run$date.log
cp -f ${tempFile2} ${targetDir}
time=`date +"%Y-%m-%d %H:%M:%S"`
echo "We have saved ${tempFile2} into ${targetDir}[${time}]">>run$date.log
else
echo "Fetal Error,$tempFile2 checked flag is not expected [${time}]">>run$date.log
fi
else
echo "Fetal Error,$tempFile2 size is not expected [${time}]">>run$date.log
fi
#
<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">2)调度函数staticMain.sh</span>
#!/bin/bash
homeUrl="http://localhost:8090/home"
targetDir="/projects/prenewsite/cn/page/home/"
workDir="/temp/temp2/"
count=1
while [ $count -ge 0 ]
do
source ${workDir}indexSave.sh $homeUrl $targetDir $workDir
sleep 20
done
#
3)执行命令脚本
nohup sh staticMain.sh >/dev/null 2>&1 &
#注意:在[] 表达式中,常见的>,<需要加转义字符,表示字符串大小比较,以acill码 位置作为比较。 不直接支持<>运算符,还有逻辑运算符|| && 它需要用-a[and] –o[or]表示