java 多线程 实时监控日志文件并实时读取新数据

日萌社

人工智能AI:Keras PyTorch MXNet TensorFlow PaddlePaddle 深度学习实战(不定时更新)


 

文章参考:https://www.jb51.net/article/116526.htm

java ScheduledExecutorService 多线程与定时任务的结合使用

 

读取文件、写出文件 请使用 字符缓冲流、字节缓冲流

File output = new File("/home/root/logs/output.log");
File readin = new File("/home/root/logs/readin.log");
BufferedReader br = new BufferedReader(new FileReader(readin),16384);
BufferedWriter bw = new BufferedWriter(new FileWriter(output),16384);
​​​​​​​String tmp = br.readLine();
bw.write(tmp + "\n");
bw.flush();
br.close();
bw.close();

测试证据

RandomAccessFile 底层使用的 StringBuffer 读取 342498 行数据 耗时206秒
BufferedReader 缓冲区 包装 FileReader 读取 342498 行数据 耗时15秒

结论

不应简单使用 RandomAccessFile 读取流、Writer 输出流
应使用 字符缓冲输入流 BufferedReader、字符缓冲输出流 BufferedWriter

===============日志信息实时生产类=================

(下面示例代码请自己修改为使用 字符缓冲输出流 BufferedWriter

package com.nginxlog;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;


// =============== 日志产生类 ====================
    /*
    执行LogSvr类,LogSvr类会启动一个线程,每5秒钟向mock.log日志文件写一次数据,
    然后再执行LogView类,LogView每隔1秒钟读一次,如果数据有变化则输出变化的部分.
    */
public class LogSvr
{
    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    /**
        将信息记录到日志文件
        @param logFile 日志文件
        @param mesInfo 信息
        @throws IOException 
     */
    public void logMsg(File logFile, String mesInfo) throws IOException
    {
        if (logFile == null)
        {
            throw new IllegalStateException("logFile can not be null!");
        }

        Writer txtWriter = new FileWriter(logFile, true);
        txtWriter.write(dateFormat.format(new Date()) + "\t" + mesInfo + "\n");
        txtWriter.flush();
    }

    public static void main(String[] args) throws Exception
    {
        final LogSvr logSvr = new LogSvr();
        final File tmpLogFile = new File("mock.log");
        if (!tmpLogFile.exists())
        {
            tmpLogFile.createNewFile();
        }

        //启动一个线程每5秒钟向日志文件写一次数据
        ScheduledExecutorService exec = Executors.newScheduledThreadPool(1);
        exec.scheduleWithFixedDelay(new Runnable()
        {
            public void run()
            {
                try
                {
                    logSvr.logMsg(tmpLogFile, "xxxxxxxxxxxxx");
                }
                catch (IOException e)
                {
                    throw new RuntimeException(e);
                }
            }
        }, 0, 5, TimeUnit.SECONDS);
    }
}

===============日志信息实时监控读取类=================

(下面示例代码请自己修改为使用 字符缓冲输入流 BufferedReader

package com.nginxlog;
import java.io.File;  
import java.io.IOException;  
import java.io.RandomAccessFile;  
import java.util.concurrent.Executors;  
import java.util.concurrent.ScheduledExecutorService;  
import java.util.concurrent.TimeUnit;  
  
public class LogView {  
 private long lastTimeFileSize = 0; //上次文件大小  
 /** 
  * 实时输出日志信息 
  * @param logFile 日志文件 
  * @throws IOException 
  */
 public void realtimeShowLog(File logFile) throws IOException
{  
/*
window 跑 main方法:
            读取和写出文件的路径都是默认项目根目录中的文件,那么只需要定义出文件名而无需写出具体路径,
            即可使用 new File("文件名") 读取和写出项目根目录中的文件。

window、linux 跑 tomcat:
            读取和写出文件的路径 需要写出 具体的文件和及其绝对路径,即 new File("/绝对路径/文件名");
*/
  //指定文件可读可写  
  final RandomAccessFile randomFile = new RandomAccessFile(logFile,"rw");  
  //启动一个线程每1秒钟读取新增的日志信息  
  ScheduledExecutorService exec = Executors.newScheduledThreadPool(1);  
  exec.scheduleWithFixedDelay(new Runnable(){  
   public void run() {  
    try {      
      //将文件记录指针定位到pos位置,一开始从0的位置开始读取
     randomFile.seek(lastTimeFileSize);  
     String tmp = "";  
     while( (tmp = randomFile.readLine())!= null) {  
      System.out.println(new String(tmp.getBytes("ISO8859-1")));  
     }  
     lastTimeFileSize = randomFile.length();  
    } catch (IOException e) {  
     throw new RuntimeException(e);  
    }  
   }  
  }, 0, 1, TimeUnit.SECONDS);  
 }  
    
 public static void main(String[] args) throws Exception {  
  LogView view = new LogView();  
  final File tmpLogFile = new File("mock.log");  
  view.realtimeShowLog(tmpLogFile);  
 }  
  
}

 

 

 

 

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

あずにゃん

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值