simd
simd

Reputation: 2019

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). 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.

Upvotes: 0

Views: 530

Answers (1)

Michal Gajdos
Michal Gajdos

Reputation: 10379

If you're not tied to pre-HTML5 technologies then you can try to accomplish your task with SSE (Server-Sent Events, see Wiki). Jersey has a support for SSE, take a look at the dedicated chapter: Server-Sent Events (SSE) Support. 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). Other clients can post messages via MessageBoardResource#postMessage method (HTTP POST call to messages). The message is then broadcasted to all connected clients.

Upvotes: 1

Related Questions