如何通过Java监听新的数据库记录 [英] How to listen new db records through java

查看:42
本文介绍了如何通过Java监听新的数据库记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前,我使用 while(true) Thread.sleep()检查数据库中的新记录并执行Java代码.

Currently I use while(true) and Thread.sleep() for checking for new records in the db and execute java code.

这里是一个例子:

public class StartCommands implements Runnable{
  private Active_Job activeJob;
  Runnable execute_command;

  public StartCommands(){
     activeJobs = new Active_Job();
  }

  @Override
  public void run(){
    int jobId = 0;

    while(true){
      //access the db and get one row from the table by the status
      jobId = activeJobs.get(Status.NEW);
      if (jobId > 0){
        activeJob.updateStatus(Status.INIT);
        execute_command = activeJob.getCommand();

        new Thread(execute_command).start();

        activeJob = new Active_Job();
        jobId = 0;
      }

      Thread.sleep(10*1000);
    } 
  }
}

我在使用此方法的代码中没有几个地方.但是我不喜欢无休止的循环,每10秒检查一次新行.

I've few places in the code that I use this method. But I dont like the endless loop and check every 10 seconds for new row.

所以我要寻找的是某种侦听器:输入新记录后-执行Java代码.有些 insert 是从应用程序执行的,有些则不是.

So what I'm looking for is some kind of listener: once new record has been entered - execute java code. Some of the inserts executed from the application and some are not.

推荐答案

MySQL(或我知道的任何SQL数据库)中都没有内置的更新侦听器",因此您必须构建自己的.

There is no builtin "update listener" in MySQL (or any SQL database I'm aware of), so you have to build your own.

请注意,在您的实现中,如果添加了两个新行,您将处理一个,等待10秒钟,然后处理下一个.您的代码每10秒不能处理多个事件.

Notice that in your implementation, if two new rows are added you will handle one, wait 10 seconds, then handle the next one. Your code cannot handle more than one event every 10 seconds.

您要做的是将数据库的轮询与工作线程的调度分开.让轮询循环每n秒唤醒一次,从数据库中读取所有新记录,然后将它们添加到工作队列中.使使用者线程正在队列中等待,并在消息出现在队列中时启动处理器.使用线程池实现.

What you want to do is separate the polling of the database from the dispatching of the worker threads. Have the polling loop wake up every n seconds, read ALL new records from the database, and add them to a work queue. Have a consumer thread that is waiting on the queue and launches processors as messages appear on the queue. using a thread pool implementation.

这篇关于如何通过Java监听新的数据库记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆