nginx服务器的access.log日志中,统计访客ip的访问次数。
我这个版本只统计前24位的数据。
还不如在linux用shell来统计,java写出来的代码太多了。
package file; import java.io.*; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; /** * 统计nginx访问日志中ip前24位的访问次数 * @author zhl * @date 2019/10/29 0029 14:03 */ public class ReadFile { static SimpleDateFormat format = new SimpleDateFormat("dd/MMM/yyyy:HH:mm:ss z",Locale.ENGLISH); static SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); /** * 开始时间 */ static String start_date ="2019-11-1 00:00:00"; /** * 结束时间 */ static String end_date = "2019-11-6 23:59:59"; /** * 文件路径 */ static String file_path = "C:\\Users\\zhuho\\Documents\\access.log"; public static void main(String[] args) throws IOException, ParseException { FileReader fr = new FileReader(file_path); BufferedReader br = new BufferedReader(fr); String tempString; int i =0; TreeMap<String, Integer> map = new TreeMap<>(); while( (tempString = br.readLine()) != null){ //System.out.println(tempString); if(tempString.matches("(.*)spider(.*)")){ //System.out.println("爬虫 continue;"); continue; } Date this_date ; { //识别日期 int date_start_index = tempString.indexOf("["); int date_end_index = tempString.indexOf("]"); String date_string = tempString.substring(date_start_index+1, date_end_index); this_date = format.parse(date_string); } //只处理在指定日期范围内的数据 if(this_date.after(df.parse(start_date)) && this_date.before(df.parse(end_date))){ /** * 111.111.111.* * ip前24位的最大长度是12个字符 */ tempString = tempString.substring(0,12); int index = tempString.lastIndexOf("."); tempString = tempString.substring(0,index); if(map.get(tempString) == null){ map.put(tempString, 1); }else{ map.put(tempString, map.get(tempString)+1); } } /*if(i>1000){ return; } i++;*/ } fr.close(); //把treemap转换为list集合利用sort排序 List<Map.Entry<String, Integer>> list=new ArrayList<Map.Entry<String,Integer>>(map.entrySet()); Collections.sort(list,new Comparator<Map.Entry<String, Integer>>() { @Override public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) { return o2.getValue()-o1.getValue();//倒序 } }); System.out.println("查询范围:"); System.out.println(start_date +"\t"+ end_date); for (Map.Entry<String, Integer> entry : list) { System.out.println(entry.getKey()+"\t"+entry.getValue()); } } }
输出:
查询范围: 2019-11-1 00:00:00 2019-11-6 23:59:59 14.215.176 2932 223.104.3 1536 117.136.38 1303 39.156.65 1242 124.64.16 370 112.34.110 323 36.102.228 290 124.64.18 273 219.143.154 254 36.110.199 251 111.206.36 220