使用多线程的Java Rest客户端

时间:2015-06-02 05:52:13

标签: java multithreading rest java-ee

我有一个java Rest Client,它会将后期数据保存到java Rest Service

我开发了泽西客户端代码,将数据发布到Rest Service。 当我执行我的客户端应用程序时

  1. 它将连接到数据库,它将执行选择查询
  2. 它将连接到Rest服务URL并将发布数据
  3. 我的代码:

    select * from Workorder
    
    for(int i =0;i<workorderList.size(); i++){
    
       WorkOrder workorder=workorderLit.get(i);
    
       WebResource webResource = client
                        .resource("http://localhost:8013/Workorderrest/rest/inbound/update");
    
       ClientResponse response = webResource.accept("application/json")
                        .type("application/json")
                        .header("Authorization", "Basic " + authStringEnc)
                        .post(ClientResponse.class, jsonData);   
    }
    

    当我从Rest Service

    收到响应时,我想将我的表列中的状态标志更改为已处理

    请问任何人。我想使用多个线程发布数据 任何建议

2 个答案:

答案 0 :(得分:2)

我试过,一个人正在为我工​​作......

ClientThread.java

package com.test;

    import javax.ws.rs.core.MediaType;

    import com.sun.jersey.api.client.Client;
    import com.sun.jersey.api.client.ClientResponse;
    import com.sun.jersey.api.client.WebResource;

    public class ClientThread extends Thread{

    Client client = null;
    WebResource resource = null;

    public ClientThread()
    {
        client = Client.create();
        resource = client.resource("http://localhost:9080/RestfulHelloExample/rest/hello/kumar");

    }
    public void run()
    {
        ClientResponse response = resource.type(MediaType.APPLICATION_XML).get(ClientResponse.class);

        if (response.getStatus() != 200) {
            throw new RuntimeException("Failed : HTTP error code : "
                 + response.getStatus());
        }

        System.out.println("Output from Server .... \n");
        String output = response.getEntity(String.class);
        System.out.println(output);             
    }
    }

TestClient.java

public class TestClient {
public static void main(String[] args) {

    ClientThread t1 = new ClientThread();
    ClientThread t2 = new ClientThread();
    t1.start();
    t2.start();

}

}

如果您有任何问题,请与我们联系。

答案 1 :(得分:1)

得到回复后

ClientResponse response = webResource.accept("application/json")
                .type("application/json")
                .header("Authorization", "Basic " + authStringEnc)
                .post(ClientResponse.class, jsonData);   

试试这个

new Thread(new Runnable() {

            @Override
            public void run() {
                if (response.getStatus() != 200) {
                       throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
                }else{
                    // your code for updating status flag in table 
                }
            }
}).start();