简体   繁体   English

球衣jax-rs资源之间的通信

[英]jersey jax-rs communication between resources

I want to implement long polling in Jersey. 我想在泽西岛实施长轮询。 I have a resource for sending messages(messages.send) and another for long polling(messages.longpoll). 我有一个发送消息的资源(messages.send)和另一个用于长轮询的资源(messages.longpoll)。 I suspend async request in messages.longpoll, but can't realize how it can be notified that new message was added, since this happens in another resource - messages.send. 我在messages.longpoll中暂停了异步请求,但无法实现如何通知它已添加新消息,因为这发生在另一个资源中-messages.send。

If you're not tied to pre-HTML5 technologies then you can try to accomplish your task with SSE (Server-Sent Events, see Wiki ). 如果您不依赖HTML5之前的技术,则可以尝试使用SSE(服务器发送事件,请参阅Wiki )完成任务。 Jersey has a support for SSE, take a look at the dedicated chapter: Server-Sent Events (SSE) Support . 泽西岛(Jersey)支持SSE,请阅读专用章节: 服务器发送事件(SSE)支持 There are also some examples available: 还有一些可用的示例:

Then your resource may look like: 然后您的资源可能如下所示:

@Path(“messages”)
@Produces(APPLICATION_JSON)
public class MessageBoardResource {

    private static SseBroadcaster broadcaster = new SseBroadcaster();

    @GET @Path(“stream”)
    @Produces(SseFeature.SERVER_SENT_EVENTS)
    public EventOutput connect() {

        EventOutput eventOutput = new EventOutput();
        broadcaster.add(eventOutput);
        return eventOutput;

    }

    @POST 
    @Consumes(MediaType.APPLICATION_JSON)
    public Response postMessage(Message message) {

        OutboundEvent event = new OutboundEvent.Builder()
                .id(getNextId())
                .mediaType(MediaType.APPLICATION_JSON_TYPE)
                .data(Message.class, message)
                .build();


        broadcaster.broadcast(event); // invokes eventOutput.write(event);

        return Response.ok().build();
    }
}

Client, that want to listen to future messages, then connects via MessageBoardResource#connect method (HTTP GET call to messages/stream ). 想要收听将来消息的客户端,然后通过MessageBoardResource#connect方法(对messages/stream HTTP GET调用)进行连接。 Other clients can post messages via MessageBoardResource#postMessage method (HTTP POST call to messages ). 其他客户端可以通过MessageBoardResource#postMessage方法发布消息(对messages HTTP POST调用)。 The message is then broadcasted to all connected clients. 然后,该消息将广播到所有连接的客户端。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM