java 监听数据库改变,如何通过Java监听新的数据库记录

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

Here is an example:

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);

}

}

}

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.

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.

解决方案

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

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.

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.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值