前言
统计网站游客数量跟登录数量还有抽奖数量
提示:以下是本篇文章正文内容,下面案例可供参考
一、项目场景介绍
游客数量:访问主页的游客数量 需要过滤重复数据
登录数量:系统登录的客户数 需要过滤重复数据
抽奖数量:系统抽过奖的客户数 需要过滤重复数据
以上所有数据每天0点刷新
二、思路以及实现代码
1.思路
游客数量通过ip来过滤重复游客,登录客户数量通过账户来过滤,数据存储进redis里,过期时间设置为距离今天晚上0点还有多少秒
如果redis不存在key,就新建key,同时设置过期时间(离今天0点还有多少秒),如果存在就加一,冗余字段登录次数
2.代码
获取游客数量(示例):
public JsonData IPinterview(HttpServletRequest request) {
//获取游客IP
String touristIP = IpUtil.getIpAddr(request);
//如果redis不存在key,就新建key,同时设置过期时间(离今天0点还有多少秒),如果存在就加一,冗余字段登录次数
if (redisUtil.hasKey(TOURIST_IP_AMOUNT)) {
if (redisUtil.hHasKey(TOURIST_IP_AMOUNT, touristIP)) {
redisUtil.hincr(TOURIST_IP_AMOUNT, touristIP, 1);
} else {
redisUtil.hset(TOURIST_IP_AMOUNT, touristIP, 1);
}
} else {
redisUtil.hset(TOURIST_IP_AMOUNT, touristIP, 1, TimeUtils.getRemainSecondsOneDay1(new Date()));
}
return JsonData.buildSuccess();
}
/**
* 获取游客IP工具类
*/
public class IpUtil {
private static final String UNKNOWN = "unknown";
private static final String LOCALHOST = "127.0.0.1";
private static final String SEPARATOR = ",";
public static String getIpAddr(HttpServletRequest request) {
System.out.println(request);
String ipAddress;
try {
ipAddress = request.getHeader("x-forwarded-for");
if (ipAddress == null || ipAddress.length() == 0 || UNKNOWN.equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("Proxy-Client-IP");
}
if (ipAddress == null || ipAddress.length() == 0 || UNKNOWN.equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("WL-Proxy-Client-IP");
}
if (ipAddress == null || ipAddress.length() == 0 || UNKNOWN.equalsIgnoreCase(ipAddress)) {
ipAddress = request.getRemoteAddr();
if (LOCALHOST.equals(ipAddress)) {
InetAddress inet = null;
try {
inet = InetAddress.getLocalHost();
} catch (Exception e) {
log.error("获取IP失败");
}
ipAddress = inet.getHostAddress();
}
}
// 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
// "***.***.***.***".length()
if (ipAddress != null && ipAddress.length() > 15) {
if (ipAddress.indexOf(SEPARATOR) > 0) {
ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
}
}
} catch (Exception e) {
ipAddress = "";
}
return ipAddress;
}
}
public class TimeUtils {
/**
* 获取距离目标时间还要多少秒
*/
public static Integer getRemainSecondsOneDay1(Date currentDate) {
LocalDateTime midnight = LocalDateTime.ofInstant(currentDate.toInstant(),
ZoneId.systemDefault()).plusDays(1).withHour(0).withMinute(0)
.withSecond(0).withNano(0);
LocalDateTime currentDateTime = LocalDateTime.ofInstant(currentDate.toInstant(),
ZoneId.systemDefault());
long seconds = ChronoUnit.SECONDS.between(currentDateTime, midnight);
return (int) seconds;
}
}
redis
总结
三种数据统计的思路其实是差不多的,只不过统计的切点不一样,游客数可以专门写一个接口给前端在首页调用,如果要统计全站游客数,建议用aop切片的形式,把需要统计的接口全部打上标签,就算重复访问,在程序里也会过滤掉重复ip.