如何自动化POST请求的Java后台服务?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (199)

处理POST请求的资源方法如下所示

@POST
@Produces({MediaType.APPLICATION_JSON})
public Response migrateToMinio(@Context UriInfo uriInfo) throws Exception {
    tiedostoService = new TiedostoService();
    attachmentService = new AttachmentService();
    List<Tiedosto> tiedostoList = tiedostoService.getAllFiles();
    List<String> responseList = new ArrayList<>();
    Response r;
    Integer newRow;
    String responseData = null;
    int i=1;
    for (Tiedosto tiedosto : tiedostoList) {
        Attachment attachment = new Attachment();
        attachment.setCustomerId(tiedosto.getCustomerId());
        attachment.setSize(tiedosto.getFileSize());
        newRow = attachmentService.createNew(attachment);
        UriBuilder builder = uriInfo.getAbsolutePathBuilder();
        if (newRow == 1) {
            builder.path(Integer.toString(i));
            r = Response.created(builder.build()).build();
            responseData = r.getLocation().toString();
            i++;
        }
        responseList.add(responseData);
    }
    String jsonString = new Gson().toJson(responseList);
    return Response.status(Response.Status.OK).entity(jsonString).build();
}

我的问题是,如何实现Java后台服务(就像运行在与服务器相同的物理机器上的客户机)?

提问于
用户回答回答于

可以使用JAX-RS客户端API将HTTP POST请求发送到localhost:

Client client = ClientBuilder.newClient();
Response res = client.target("http://localhost/your/path/here").request("application/json").post(/* ... Entity that goes in the message body ... */);

立即ExecutorService触发第一个(一组)HTTP请求,然后使用an 以POST固定速率(或固定间隔,根据您的特定需求)触发HTTP :

public class ClientService {

    private static final ScheduledExecutorService EXECUTOR = Executors.newScheduledThreadPool(1);

    private static final long INITIAL_DELAY = 10_000;
    private static final long UPDATE_RATE = 10_000;

    public static void main(String[] args) {
        // Fire first (full?) update trigger here
        fireInitialMigration();
        // For subsequent (incremental?) updates, schedule an HTTP POST to occur at a fixed rate:
        EXECUTOR.scheduleAtFixedRate(() -> fireSubsequentUpdate(), INITIAL_DELAY, UPDATE_RATE, TimeUnit.MILLISECONDS);
        // Keep main thread alive
        while (true);
    }

    private static void fireInitialMigration() {
        Client client = ClientBuilder.newClient();
        Response res = client.target("http://localhost/your/path/here").request("application/json").post(/* ... Entity that goes in the message body ... */);
    }

    private static void fireSubsequentUpdate() {
        // Similar to initialMigration(), but change Entity/set of HTTP POSTs according to your needs.
    }
}

扫码关注云+社区

领取腾讯云代金券