querying DB in a loop continuously in java

白昼怎懂夜的黑 提交于 2020-07-09 08:39:48

问题


Is it advisable to query a database continuously in a loop, to get any new data which is added to specific table?

I have below a piece of code:

  while(true)
      try{
         // get connection
         // execute only "SELECT" query
       }
      catch(Exception e){}
      finally{// close connection

      }
         //Sleep 5 sec's
      }

回答1:


It is a simple approach that works in many cases. Make sure that the select statement you use doesn't put as little load as possible on the database.

The better (but more difficult to setup) variant would be either to use some mechanism to get actively informed by the database about changes. Some databases can for example can send information with some queuing mechanism, which again could be triggered using a database trigger.




回答2:


Querying database in loop is not advisable but if you need the same you can daemonize your program.




回答3:


If longer then 5 s a timer would be appropriate.

For a kind of staying totally up-to-date:

Triggers and cascading inserts/deletes can propagate data inside the database itself.

Otherwise before altering the database, issue messages in a message queue. This not necessarily needs to be a Message Queue (capitals) but can be any kind of queue, like a publish/subscribe mechanism or whatever.




回答4:


On one hand, if your database has a low change rate then it would be better to use/implement a notification system. Many RDBMS have notification features (Oracle's Database Change Notification, Postgres' Asynchronous Notifications, ...), and if your RDBMS does not have them, it is easy to implement/emulate using triggers (if your RDBMS support them).

On the other hand, if the change rate is very high then your solution is preferable. But you need to adjust carefully the interval time and you must note: reading on intervals to detect changes has a negative collateral effect.

  • Using/implementing a notification system it is easy to inform the program what has been changed. (A new row X inserted on table A, a new updated row Y on table B, …).
  • But if you read your data on intervals, it is not easy to determine what has been changed. Then you have two options:

    a) you must not only read but load/process all information every interval;

    b) or you must not only read but compare database data with memory resident data to determine what has changed every interval.



来源:https://stackoverflow.com/questions/31109989/querying-db-in-a-loop-continuously-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!