其他
Spring Boot + Echarts实现用户访问地图可视化
在常见的电商、新闻、社交网站等,合理运用运营成本才能最大化输出自己的产品,其中最常见的功能就有针对不同访问热度的城市制定不同的运营手段,因此我们掌握用户城市分布情况至关重要。
根据ip获取城市的方式
淘宝、新浪等常年提供根据ip获取城市的接口,但是隔一段时间会出现接口地址更改的情况,也有一定的限流开源纯真ip库:不断迭代更新ip库内容,一般场景下足以使用,自主可控。(下载qqwry.dat库)思路
首先需要获取用户请求的ip地址,我们对该方法进行简单封装:public static String getIpAddress(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}
}
封装纯真ip的解析工具,根据ip获取请求地址所在城市,github有大量实现版本,我们这里不做赘述,具体代码见文末源码
public IPZone findIP(final String ip) {
final long ipNum = toNumericIP(ip);
final QIndex idx = searchIndex(ipNum);
if (idx == null) {
return new IPZone(ip);
}
return readIP(ip, idx);
}
* 登录拦截器
*/
@Slf4j
public class MyLoginInterceptor implements HandlerInterceptor {
private static final String LOGIN_PATH = "/user/login";
private static Map<String, AtomicInteger> visitCount;
private static final QQWry qqWry;
static {
visitCount = new HashMap<>(31);
qqWry = new QQWry();
}
//展示访问数量不是精确指标,如果要做到完全正确需要使用锁,防止计数存在并发问题
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
log.info("【MyLoginInterceptor】调用了:{}", request.getRequestURI());
if (request.getRequestURI().equals(LOGIN_PATH)) {
String ipAddress = IPUtil.getIpAddress(request);
String province = qqWry.findIP(ipAddress).getMainInfo();
if (visitCount.containsKey(province)) {
visitCount.put(province,new AtomicInteger(visitCount.get(province).incrementAndGet()));
} else {
visitCount.put(province,new AtomicInteger());
}
}
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response,
Object handler, ModelAndView modelAndView) throws Exception {}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
Object handler, Exception ex){}
}
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new MyLoginInterceptor());
}
}
登录controller模拟逻辑,注意:如果想看效果图需要自己写线程用不同的虚拟ip进行访问url,从而达到在不同城市访问接口的效果。
public class LoginController {
@GetMapping("login")
public String login() {
//登录逻辑
return "success";
}
}