这个参考了csdn一个首页访问量的demo,在这个基础上进行了些并发修改,框架采用了spring,数据库sqlserver,当然任何数据库都可以,记得把包自己加进去,我这只有sqlserver和mysql的,oracle的自己加个包就行。
核心代码,很简单,Commons.count方法是得到一个静态的list,为了防止高并发下内存溢出,没有采集按照时间来提交,而采取的是访问5次commit,当然是为了测试方便,这个按照需求来。用ajax进行回调,先加载的首页,不影响首页的相应速度。
测试用的jmeter,并发线程1万访问还是可以的,并发1千相当轻松。
//保存当前访问记录 5条commit一次
try {
synchronized(Commons.count){
Commons.count.add(logBean);
if(Commons.count.size()==5){
logService.saveCommons(Commons.count);
Commons.count.clear();
}
}
//logService.saveLog(logBean); //这个是单个保存
} catch (Exception e) {
e.printStackTrace();
logger.error(e.getMessage());
}
jsp
<%@ page language="java" contentType="text/html;" pageEncoding="utf-8" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>index count</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<script language="javascript" src="jquery-2.1.4.min.js"></script>
</head>
<body>
<div>这是个首页</div>
<br>
<br>
<div id="count">
</div>
</body>
<script type="text/javascript">
$(function(){
$.ajax( {
url:'<%=basePath%>mst/CountServlet',// 跳转到 action
traditional: true,
type:'post',
success: function(data){
var json=JSON.parse(data);
$("#count").append(" <h4>本首页访问量为"+json.counts+"人次</h4>");
}
});
})
</script>
</html>
web.xml设置filter,我设置的这个过滤器只过滤首页的,根据需求可以定义需要过滤的页面。
<filter>
<filter-name>logFilter</filter-name>
<filter-class>com.filter.LogFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>logFilter</filter-name>
<url-pattern>/index.jsp</url-pattern>
</filter-mapping>
<!-- ajax 统计首页访问量-->
<servlet>
<servlet-name>CountServlet</servlet-name>
<servlet-class>com.service.impl.Count</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CountServlet</servlet-name>
<url-pattern>/mst/CountServlet</url-pattern>
</servlet-mapping>
下载的链接如下,其实上面核心都说明了,其实这个demo可扩展性很大,我是懒的弄了。并且除了自己实现,还可以用直接调用像百度统计这样的接口。
下载请点这里
为了防止下载链接问题我直接贴
http://download.youkuaiyun.com/detail/ilovexiaou/9619002