首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何实现异步处理

如何实现异步处理
EN

Stack Overflow用户
提问于 2013-01-07 09:06:51
回答 2查看 467关注 0票数 1

我希望在我的Java程序中传递一条异步消息,所以作为第一步,它应该持续监视DB中某些表的更改。当有新的传入消息时,它应该显示它。这应该是重复的进程,只要应用程序正在运行。

我可以知道如何对下面的代码进行此操作,其中包含轮询方法,它必须每6秒无限地调用自己,并且还应该在数据库中找到新的传入消息。

下面是代码片段:

代码语言:javascript
复制
public class PollingSynchronizer implements Runnable {

private Collection<KPIMessage> incomingMessages;
private Connection dbConnection;


/**
 * Constructor. Requires to provide a reference to the KA message queue
 * 
 * @param incomingMessages reference to message queue
 * 
 */
   public PollingSynchronizer(Collection<KpiMessage> incomingMessages, Connection dbConnection) {
    super();
    this.incomingMessages = incomingMessages;
    this.dbConnection = dbConnection;
}

private int sequenceId;

public int getSequenceId() {
    return sequenceId;
}

public void setSequenceId(int sequenceId) {
    this.sequenceId = sequenceId;
}



@Override
/**
 * The method which runs Polling action and record the time at which it is done
 * 
 */
public void run() {
    try {


           incomingMessages.addAll(fullPoll());
            System.out.println("waiting 6 seconds");

            //perform this operation in a loop
            Thread.sleep(6000);

    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } 
    Date currentDate = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS");
//  System.out.println(sdf.format(currentDate) + " " + msg);
}

/**
 * Method which defines polling of the database and also count the number of Queries
 * @return 
 * @throws Exception
 */
public List<KpiMessage> fullPoll() throws Exception {

//  int sequenceID = 0;
    Statement st = dbConnection.createStatement();

    ResultSet rs = st.executeQuery("select * from msg_new_to_bde where ACTION = 804 order by SEQ DESC");
        List<KpiMessage> pojoCol = new ArrayList<KpiMessage>();
        while (rs.next()) {
            KpiMessage filedClass = convertRecordsetToPojo(rs);
            pojoCol.add(filedClass);
        }

        return pojoCol;
        }

/**
 * Converts a provided record-set to a {@link KpiMessage}.
 * 
 * The following attributes are copied from record-set to pojo:
 * 
 * <ul>
 * <li>SEQ</li>
 * <li>TABLENAME</li>
 * <li>ENTRYTIME</li>
 * <li>STATUS</li>
 * </ul>
 * 
 * @param rs
 *            the recordset to convert
 * @return the converted pojo class object
 * @throws SQLException
 *             if an sql error occurrs during processing of recordset
 */
private KpiMessage convertRecordsetToPojo(ResultSet rs) throws SQLException {

    KpiMessage msg = new KpiMessage();
    int sequence = rs.getInt("SEQ");
    msg.setSequence(sequence);
    int action = rs.getInt("ACTION");
    msg.setAction(action);
    String tablename = rs.getString("TABLENAME");
    msg.setTableName(tablename);
    Timestamp entrytime = rs.getTimestamp("ENTRYTIME");
    Date entryTime = new Date(entrytime.getTime());
    msg.setEntryTime(entryTime);
    Timestamp processingtime = rs.getTimestamp("PROCESSINGTIME");
    if (processingtime != null) {
        Date processingTime = new Date(processingtime.getTime());
        msg.setProcessingTime(processingTime);
    }
    String keyInfo1 = rs.getString("KEYINFO1");
    msg.setKeyInfo1(keyInfo1);
    String keyInfo2 = rs.getString("KEYINFO2");
    msg.setKeyInfo2(keyInfo2);
    return msg;
}
}

在这里,序列id是表中唯一的id,它在新的传入消息到达时不断增加。

P.S:“善意的要求:请给出给负号的理由(拇指向下),这样我才能清楚地解释我的问题。”

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-01-07 09:35:25

简单地把它放入一个时间(True)循环中。

代码语言:javascript
复制
public void run() {
    while(true){
        try {


               incomingMessages.addAll(fullPoll());
                System.out.println("waiting 6 seconds");

                //perform this operation in a loop
                Thread.sleep(6000);

        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
        Date currentDate = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS");
    //  System.out.println(sdf.format(currentDate) + " " + msg);
   }
}

希望您已经将Runnable作为一个新线程启动。

对于新的和更新的消息,您需要一个字段,例如数据库中的"last_update“。当您检查新消息时,需要修改SQL语句将新消息转换为"where last_update > $lastCheckedDate",其中设置了lastCheckedDate

MAybe您还想在Java中阅读一些关于并发性的内容:http://docs.oracle.com/javase/tutorial/essential/concurrency/

票数 1
EN

Stack Overflow用户

发布于 2013-01-07 09:44:15

使用while循环是一种方法,但我认为最好避免使用这种方法(有很多事情需要处理,比如事务等)。

如果你真的需要做这种重复的事情,可以考虑使用调度器。Spring3.xdo有内置的调度程序,或者您也可以使用Quartz。

更好的方法是避免像这样的投票。更新数据时,是否可以将消息放入JMS队列,以便在JMS队列中有消息时(通过消息驱动的bean)调用您的逻辑?(只有一种可能的方法,有很多类似的方法可做)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14192777

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档