在Java中使用RESTful Web服务上的线程

时间:2014-11-11 00:33:09

标签: multithreading web-services rest web

我有一个RESTful Web服务的问题,我在php中有一个客户端用Java调用RESTful服务。在我的RESTful服务中,我有一个Post方法,它执行更新查询以修改表中包含10000条记录的所有行。我想用线程来做这件事。有可能这样做吗?请帮帮我,我是Java的新手。感谢。

好的我在服务层执行此操作:

for(int i = 0; i < 10; i++)
{
    startRow = i*1000;
    finalRow = i*1000 + 1000;
    Runnable process = new ProcessRecords(startRow , finalRow);
    executor.execute(process);                    
}

// Wait until all threads are finish
while (!executor.isTerminated()) {

}
System.out.println("\n All threads finished");

我正在调用此类(ProcessRecords)来执行更新:

public ProcessRecords (int start, int final)
{
    startRow = start;
    finalRow = final;
}

@Override
public void run(){

    try {

        ConsultUniversity consult = new ConsultUniversity ();
        consult.averangeGrade(startRow, finalRow);

    } catch (Exception ex) {
        Logger.getLogger(Procesos.class.getName()).log(Level.SEVERE, null, ex);
    }
}

然后在我的数据层中,我在我的方法“averangeGrade”中执行此操作:

 try {
        conn = UniversityConection();//This is my conection

        query = "SELECT * FROM grades LIMIT " + filaInicial + "," + filaFinal;            
        prepStatement = conn.prepareStatement(query);

        rs = prepStatement.executeQuery(query);  

        rsmd = rs.getMetaData();

        while(rs.next())
        {
            averange = (rs.getInt("nFirGrd") + rs.getInt("nSecGrd") + 
                               rs.getInt("nThrGrd"))/3; //the averange of three grades

            query = "UPDATE grades SET nFinGrd = ? WHERE cCodAlu = ?";

            prepStatement = conn.prepareStatement(query);
            prepStatement.setInt(1, averange);
            prepStatement.setString(2, rs.getString("cCodAlu"));

            prepStatement.executeUpdate();

            System.out.println("Record " + rs.getString("cCodAlu") + 
                                       " modified");
        }               

        conn.close(); //close connection    

    }

然后当我执行我的客户端时,我的服务会对顶行进行更新,比如50行,然后返回消息,就像所有进程都已完成一样,我不知道为什么。我认为不会等到所有线程都完成,但有代码,那为什么会发生这种情况?请帮我。谢谢。

1 个答案:

答案 0 :(得分:2)

当然,这是可能的。 您熟悉Java提供的并发API吗?

从高层来看,您必须编写处理Http POST的代码。在此代码中,您可以实例化任意数量的线程(线程池),并且池的每个线程都会对要更新的行的子集进行更新。 例如,您可以启动10个线程,每个线程仅在1000行上进行更新。

此外:

  1. 我会在应用程序启动时设置线程池,所以每次执行POST时它都会使用已经创建的池,并且每次都不会实例化新的池(它太贵了)
  2. 要为每个线程分配行的子集,您必须使用LIMIT和START sql子句,以便您选择子集。每个线程将根据此2个参数
  3. 进行不同的查询

    在代码中:

    // instantiate the pool
    ExecutorService pool=Executors.newFixedThreadPool(poolSize);
    // run the task to execute in parallel, specificying the subset of rows
    pool.execute(new UpdateHandler(limit,skip));
    
    // below you find a prototype of the async thread task
    class Handler implements Runnable {
       private final int skip;
       private final int limit;
       Handler(int limit, int skip) { ... }
    
       public void run() {
         // specify the code that runs the query here
       }
     }
    

    您可以找到文档herehere 希望这会有所帮助。

相关问题