Eri*_*uez 1 rest multithreading web-services 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");
Run Code Online (Sandbox Code Playgroud)
我正在调用这个类 (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);
}
}
Run Code Online (Sandbox Code Playgroud)
然后在我的数据层中,我在我的方法“averageGrade”中执行此操作:
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
}
Run Code Online (Sandbox Code Playgroud)
然后当我执行我的客户端时,我的服务会更新最上面的行,比如 50 行,然后返回消息,比如所有进程都完成了,我不知道为什么。我认为不是等到所有线程都完成后,但是有代码,那为什么会发生这种情况呢?。请帮我。谢谢你。
当然,这是可能的。你熟悉Java提供的并发API吗?
从高层次的角度来看,您必须编写处理该 Http POST 的代码。在这段代码中,您可以实例化任意数量的线程(一个线程池),池中的每个线程都会对要更新的行的子集进行更新。例如,您可以启动 10 个线程,每个线程仅对 1000 行进行更新。
此外:
在代码中:
// 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
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17221 次 |
| 最近记录: |