在这里,该方法读取具有唯一 ID 且序列号不断增加的数据库,因为我是 java 初学者,我能知道如何实现这种重复轮询并每次检查新的传入消息。
public void run() {
int seqId = 0;
while(true) {
List<KpiMessage> list = null;
try {
list = fullPoll(seqId);
if (!list.isEmpty()) {
seqId = list.get(0).getSequence();
incomingMessages.addAll(list);
System.out.println("waiting 3 seconds");
System.out.println("new incoming message");
Thread.sleep(3000);
}
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
//Method which defines polling of the database and also count the number of Queries
public List<KpiMessage> fullPoll(int lastSeq) throws Exception {
Statement st = dbConnection.createStatement();
ResultSet rs = st.executeQuery("select * from msg_new_to_bde where ACTION = 804 and SEQ >" + lastSeq + "order by SEQ DESC");
List<KpiMessage> pojoCol = new ArrayList<KpiMessage>();
while (rs.next()) {
KpiMessage filedClass = convertRecordsetToPojo(rs);
pojoCol.add(filedClass);
}
for (KpiMessage pojoClass : pojoCol) {
System.out.print(" " + pojoClass.getSequence());
System.out.print(" " + pojoClass.getTableName());
System.out.print(" " + pojoClass.getAction());
System.out.print(" " + pojoClass.getKeyInfo1());
System.out.print(" " + pojoClass.getKeyInfo2());
System.out.println(" " + pojoClass.getEntryTime());
}
// return seqId;
return pojoCol;
}
我的目标是从数据库中轮询表并检查是否有新的传入消息,我可以从表中的 Header 字段 SequenceID 中找到该消息,该字段是唯一的,并且会不断增加新条目。现在我的问题是
1.假设我第一次轮询后,它会读取所有条目并使线程休眠 6 秒,同时如何获取新的传入数据并再次轮询?
2.还有如何添加新数据,当它第二次轮询并将新数据传递给另一个类时。