JAX-RS中的发布者/订阅者-列表未更新

时间:2018-09-05 05:46:14

标签: java jax-rs publish-subscribe

所以我试图在JAX-RS中实现发布者/订阅者模式,但是似乎在订阅者订阅之后,发布者找不到订阅。

服务器代码:

@GET
@Path("{id}/subscribe")
public void subscribe(@Suspended AsyncResponse asyncResponse, @PathParam("id") Long id) {
    if (responses.containsKey(id)) {
        responses.get(id).add(asyncResponse);
    } else {
        List<AsyncResponse> newList = new ArrayList<>();
        newList.add(asyncResponse);
        responses.put(id, newList);
    }
    System.out.println(responses.size());
}

@POST
@Path("{id}/publish")
@Consumes(MediaType.TEXT_PLAIN)
public void publish(String message, @PathParam("id") Long id) {
    System.out.println(responses.size());
    List<AsyncResponse> responseList = responses.get(id);
    if (responseList == null) {
        return;
    }
    for (AsyncResponse response : responseList) {
        response.resume(message);
    }
    responseList.clear();
}

客户代码:

public void subscribeToConcertNews(ConcertDTO concertDTO) {
    Response response = null;
    String url = CONCERT_URL + "/" + concertDTO.getId() + "/subscribe";

    ClientBuilder.newClient().target(url)
            .request()
            .async()
            .get(new InvocationCallback<String>() {
                @Override
                public void completed(String s) {
                    System.out.println(s);
                    _client.target(CONCERT_URL + "/" + concertDTO.getId() + "/subscribe")
                            .request()
                            .async()
                            .get(this);
                }

                @Override
                public void failed(Throwable throwable) {
                    throw new ServiceException("");
                }
            });


}

public void publishToConcertNews(ConcertDTO concertDTO, String message) {
    Response response = _client.target(CONCERT_URL + "/" + concertDTO.getId() + "/publish")
            .request()
            .post(Entity.entity("News!", MediaType.TEXT_PLAIN));

}

测试代码:

ConcertDTO concertDTO = new ConcertDTO(1L, "123", new HashSet<>(), new HashMap<>(), new HashSet<>());
    _service.subscribeToConcertNews(concertDTO);
    _service.publishToConcertNews(concertDTO, "213123");

订阅后,地图的大小为1,但是尝试发布新闻,因为它读取的用于保存响应的地图大小为0。因此,存储在地图中的AsyncResponse消失了。任何帮助将不胜感激!

0 个答案:

没有答案