java实时监听日志写入kafka(多目录)
目的
源码
- import java.io.BufferedReader;
- import java.io.BufferedWriter;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.io.FileReader;
- import java.io.FileWriter;
- import java.io.IOException;
- import java.io.LineNumberReader;
- import java.util.ArrayList;
- import java.util.Collection;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Properties;
- import java.util.Random;
- import kafka.javaapi.producer.Producer;
- import kafka.producer.KeyedMessage;
- import kafka.producer.ProducerConfig;
- ;
- public class XTail_Line {
- public static class TailFileThread extends Thread
- {
- File file;
- LineNumberReader randomFile=null;
- String newfile=null;
- String thisfile=null;
- String prefile=null;
- private long lastTimeFileSize = 0;
- private String drname=null;
- int ln=0;
- int beginln=0;
- private Producer<String,String> inner;
- java.util.Random ran = new Random();
- String topicname=null;
- public TailFileThread(String path,String drname,String topicname) throws FileNotFoundException, IOException
- {
- file=new File(path);
- this.drname=drname;
- this.topicname=topicname;
- Properties properties = new Properties();
- // properties.load(ClassLoader.getSystemResourceAsStream("producer.properties"));
- properties.load(new FileInputStream("producer.properties"));
- ProducerConfig config = new ProducerConfig(properties);
- inner = new Producer<String, String>(config);
- }
- public void send(String topicName,String message) {
- if(topicName == null || message == null){
- return;
- }
- // KeyedMessage<String, String> km = new KeyedMessage<String, String>(topicName,message);
- //随机作为key,hash分散到各个分区
- KeyedMessage<String, String> km = new KeyedMessage<String, String>(topicName,String.valueOf(ran.nextInt(9)),message);
- // KeyedMessage<String, String> km = new KeyedMessage<String, String>(topicName,message,message);
- inner.send(km);
- }
- public void send(String topicName,Collection<String> messages) {
- if(topicName == null || messages == null){
- return;
- }
- if(messages.isEmpty()){
- return;
- }
- List<KeyedMessage<String, String>> kms = new ArrayList<KeyedMessage<String, String>>();
- for(String entry : messages){
- KeyedMessage<String, String> km = new KeyedMessage<String, String>(topicName,entry);
- kms.add(km);
- }
- inner.send(kms);
- }
- public void close(){
- inner.close();
- }
- public String getNewFile(File file)
- {
- File[] fs=file.listFiles();
- long maxtime=0;
- String newfilename="";
- for (int i=0;i<fs.length;i++)
- {
- if (fs[i].isFile()&&fs[i].lastModified()>maxtime)
- {
- maxtime=fs[i].lastModified();
- newfilename=fs[i].getAbsolutePath();
- }
- }
- return newfilename;
- }
- //写入文件名及行号
- public void writePosition(String path,int rn)
- {
- try {
- BufferedWriter out = new BufferedWriter(new FileWriter(drname+".position"));
- out.write(path+","+rn);
- out.close();
- } catch (IOException e) {
- }
- }
- public void run()
- {
- thisfile=getNewFile(file);
- prefile=thisfile;
- //访问position文件,如果记录了文件路径,及行号,则定位,否则使用最新的文件
- try {
- BufferedReader br=new BufferedReader(new FileReader(drname+".position"));
- String line=br.readLine();
- if (line!=null &&line.contains(","))
- {
- thisfile=line.split(",")[0];
- prefile=thisfile;
- beginln=Integer.parseInt(line.split(",")[1]);
- }
- } catch (FileNotFoundException e2) {
- // TODO Auto-generated catch block
- e2.printStackTrace();
- }
- catch (IOException e2) {
- // TODO Auto-generated catch block
- e2.printStackTrace();
- }
- //指定文件可读可写
- try {
- randomFile = new LineNumberReader(new FileReader(thisfile));
- } catch (FileNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- while (true)
- {
- try {
- Thread.sleep(100);
- //调用interrupt方法后
- if(isInterrupted())
- {
- System.out.println("Interrupted...");
- break;
- }
- } catch (InterruptedException e1) {
- // TODO Auto-generated catch block
- e1.printStackTrace();
- }
- try {
- //获得变化部分的
- // randomFile.seek(lastTimeFileSize);
- String tmp = "";
- while( (tmp = randomFile.readLine())!= null) {
- int currln=randomFile.getLineNumber();
- //beginln默认为0
- if (currln>beginln)
- send(topicname,new String(tmp.getBytes("utf8")));
- ln++;
- //每发生一条写一次影响效率
- if (ln>100)
- {
- writePosition(thisfile,currln);
- ln=0;
- }
- }
- thisfile=getNewFile(file);
- if(!thisfile.equals(prefile))
- {
- randomFile.close();
- randomFile = new LineNumberReader(new FileReader(thisfile));
- prefile=thisfile;
- beginln=0;
- }
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
- }
- }
- public static void main(String[] args) throws Exception {
- /*
- LogView view = new LogView();
- final File tmpLogFile = new File("D:\\test.txt");
- view.realtimeShowLog(tmpLogFile);
- */
- if (args.length!=2)
- {
- System.out.println("usage:topicname pathname");
- System.exit(1);
- }
- String topicname=args[0];
- String pathname=args[1];
- HashMap<String,TailFileThread> hm=new HashMap<String,TailFileThread>();
- File tmpLogFile = new File(pathname);
- File[] fs=tmpLogFile.listFiles();
- while (true)
- {
- fs=tmpLogFile.listFiles();
- for (int i=0;i<fs.length;i++)
- {
- if(fs[i].isDirectory())
- {
- String path=fs[i].getAbsolutePath();
- //以drname作为position文件名
- String drname=fs[i].getName();
- //如果该目录对应的处理线程已经存在,判断是否存活
- if (drname.contains("xx") || drname.contains("yy") || drname.contains("zz") || drname.contains("aa")
- )
- {
- if (hm.containsKey(path))
- {
- if (!hm.get(path).isAlive())
- {
- hm.get(path).interrupt();
- TailFileThread tt=new TailFileThread(path,drname,topicname);
- tt.start();
- hm.put(path, tt);
- }
- }
- //如果不存在,新建
- else
- {
- TailFileThread tt=new TailFileThread(path,drname,topicname);
- tt.start();
- hm.put(path, tt);
- }
- }
- } //System.out.println(fs[i].getAbsolutePath());
- }
- Thread.sleep(100);
- }
- }
- }
转:http://blog.csdn.net/u011750989/article/details/21957741
java实时监听日志写入kafka(多目录)的更多相关文章
- java实时监听日志写入kafka(转)
原文链接:http://www.sjsjw.com/kf_cloud/article/020376ABA013802.asp 目的 实时监听某目录下的日志文件,如有新文件切换到新文件,并同步写入kaf ...
- java实时监听日志写入kafka
目的 实时监听某目录下的日志文件,如有新文件切换到新文件,并同步写入kafka,同时记录日志文件的行位置,以应对进程异常退出,能从上次的文件位置开始读取(考虑到效率,这里是每100条记一次,可调整) ...
- 20180530利用Maxwell组件实时监听Mysql的binlog日志
转自:https://blog.csdn.net/qq_30921461/article/details/78320750 http://kafka.apache.org/quickstart htt ...
- Java实现系统目录实时监听更新。
SDK1.7新增的nio WatchService能完美解决这个问题.美中不足是如果部署在window系统下会出现莫名其妙的文件夹占用异常导致子目录监听失效,linux下则完美运行.这个问题着实让人头 ...
- js 实时监听input中值变化
注意:用到了jquery需要引入jquery.min.js. 需求: 1.每个地方需要分别打分,总分为100; 2.第一个打分总分为40; 3.第二个打分总分为60. 注意:需要判断null.&quo ...
- ORACLE清理、截断监听日志文件(listener.log)
在ORACLE数据库中,如果不对监听日志文件(listener.log)进行截断,那么监听日志文件(listener.log)会变得越来越大,想必不少人听说过关于"LISTENER.LOG日 ...
- Java线程监听,意外退出线程后自动重启
Java线程监听,意外退出线程后自动重启 某日,天朗气清,回公司,未到9点,刷微博,顿觉问题泛滥,惊恐万分! 前一天写了一个微博爬行程序,主要工作原理就是每隔2分钟爬行一次微博,获取某N个关注朋友微博 ...
- Android实时监听网络状态
Android实时监听网络状态(1) 其实手机在网络方面的的监听也比较重要,有时候我们必须实时监控这个程序的实时网络状态,android在网络断开与连接的时候都会发出广播,我们通过接收系统的广播就 ...
- Oracle数据库运维:要对监听日志文件(listener.log)进行定期清理,如果不定期清理,会遇到下面一些麻烦
原文链接: http://www.lookdaima.com/WebForms/WebPages/Blanks/Pm/Docs/DocItemDetail.aspx?EmPreviewTypeV=2& ...
随机推荐
- iDempiere 使用指南 插件安装过程
Created by 蓝色布鲁斯,QQ32876341,blog http://www.cnblogs.com/zzyan/ iDempiere官方中文wiki主页 http://wiki.idemp ...
- Struts1.x 用户登录模块的实现
页面验证部分: <%@ page language="java" contentType="text/html; charset=UTF-8" pageE ...
- Java—数组和方法
数组 声明数组 数组类型[] 数组名;or 数据类型 数组名[]; 如:int[] scores; 分配空间 数组名 = new 数据类型[数组长度];如:scores = new int[5]; 以 ...
- Azure 6 月新公布
Azure 6 月新发布:磁盘加密预览版 , CDN 用户上传 HTTPS 自有证书及价格调整. Azure 磁盘加密预览版现已在中国发布 Azure 磁盘加密预览版已对 Azure 中国云地区的 W ...
- python3绘图示例6-2(基于matplotlib,绘图流程介绍及设置等)
#!/usr/bin/env python# -*- coding:utf-8 -*- import os import numpy as npimport matplotlib as mpltfro ...
- Linux文件种类与扩展名
一.文件种类 1)普通文件:ls -al第一个字符为[-]的 纯文本文件(ASCII) 二进制文件(binary):Linux中的可执行文件 数据格式文件(data):特定格式的文件,如:Linux登 ...
- COGS 182. [USACO Jan07] 均衡队形
★★ 输入文件:lineup.in 输出文件:lineup.out 简单对比时间限制:4 s 内存限制:128 MB 题目描述 农夫约翰的 N (1 ≤ N ≤ 50,000) 头奶牛 ...
- 2018.8.3 Java中容易犯错误的问题思考与总结
Java容易犯错误的问题思考 float型 float f = 3.4 是否正确 不正确,应该用强制类型转换.如下所示:float f = (float)3.4 或float f = 3.4f 在ja ...
- ROS根据访问不同的网址,走不同的路由策略的脚本
脚本如下,可以10s一循环计划执行 :global tmpaaa [/ip firewall address-list find list=Not-To-Guowai];foreach i in $t ...
- Python 初始—(列表)
列表切片 数组data=[a,b,c,d,e] print(data[1,3])#取出b,c , 如果用-号切片则是反向取数,那么去取出来的数为data[-3,-1],如果是0则默认不填 列表追加 d ...