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& ...
随机推荐
- 夜色的 cocos2d-x 开发笔记 02
本章我们让飞机发射子弹,因此我们要写这样一个方法 子弹资源:欢迎下载 很详细的注释吧,现在有几个地方报错,.h文件里面一定要先声明 这里是本章所有的新方法,你可以一次声明全部,嗯,还有个报错应该是我们 ...
- Razor 语法糖常规用法
1.隐匿代码表达式 例: @model.name 会将表达式的值计算并写入到响应中,输入时采用html编码方式 2.显示表达式 例:@(model.name)会将输入@model.name字符串 3. ...
- python的元组
Python的元组和列表很相似,只是元组一旦定义就无法修改,比如定义一个学生的元组: names = ('alex','jack') print(names)#('alex', 'jack') pri ...
- Bootstrap开发
1.BootStrap开发工具 任意前端工具 专门Bootstrap工具:Jetstrap(下载地址:jetstrap.com) 2.官网: www.bootcss.com(“下载Bootstrap” ...
- (原创)北美信用卡(Credit Card)个人使用心得与总结(个人理财版) [精华]
http://forum.chasedream.com/thread-766972-1-1.html 本人2010年 8月F1 二度来美,现在credit score 在724-728之间浮动,最高的 ...
- 使用nodejs创建加入用户验证的websocket服务
使用nodejs创建websocket服务是非常简单的(”ws”模块等),网上教程也很多.websocket服务默认没有连接验证,再加上它支持跨域连接,这样就存在“盗连”和并发攻击的风险. nodej ...
- 在ABAP里取得一个数据库表记录数的两种方法
方法1:使用函数EM_GET_NUMBER_OF_ENTRIES 这个函数使用起来很简单,只需要将想查询的数据库表名称维护进输入参数IT_TABLES: 上图说明这个函数支持批量操作,我查询的两张表名 ...
- MD5的32位加密方法
/// <summary> /// MD532位加密方式 /// </summary> /// <param name="str">用户原始密码 ...
- eclipse 集成jdk
最近想整合一个工具,eplise中包含了 pc 自动化可用的一套环境,让其他测试人员,下载下来就可以用,不需要在进行安装其他东西,jdk安装也不需要,这事可有些犯难,eplise集成了svn和test ...
- Netbackup:nbu常见错误及故障解决
Veritas Netbackup 提供了强大的故障响应功能, 能够有效及时的处理 各种备份故障.主要有备份状态码(status) .错误信息.报告信息及调试日志.下面我们主要针对备份状态码讲解下各种 ...