I am currently converting a NodeJS project to Java. At the moment I am detained in a problem that I have not found a solution. In my Node project, I have a function that works with EventEmitter(require('events')) and Net Sockets (require("net")), and uses the "emit" functions to send messages and "on" to receive. How can I do the same in Java ???
Event Emitter in Java
5k Views Asked by Randy Miguel Gómez Rodríguez AtThere are 3 best solutions below

For receive messages with GET method:
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@Path("/helloworld")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class HelloWorldRest {
@GET
public Response sayHello() {
return Response.ok("Hello World desde el API REST",MediaType.APPLICATION_JSON).build();
}
}
For send messages with POST method:
@POST
public Response createUser(User userRequest) {
userRequest.setId(users.size()+1l);
this.users.add(userRequest);
return Response.ok(userRequest).build();
}

This really depends on how this application is scaled. You have a few choices:
1. REST Instead of emit you can invoke a REST API to send the event. To receive you can have a service hosted that the other party would invoke once they are done with the event.
One thing to watch-out for in this approach is error-handling. What would you want to do if your event was not emitted because the REST API was down or if it timed out. If you cannot propagate this error to the client and have them retry... then you will need to implement a retry mechanism.
2. In-memory queue If this is a single-instance application where you just want to emit events move to the next task at hand while serving the request and there are no other instances that would interfere or be impacted by this work then you can choose to use an in-memory queue. You would need a listener for the same and a similar setup to receive your events. This is not really scalable if you want other instances that are free-to-serve to help out with one of the events. Also if for any reason this JVM dies in-flight the request will land in and error (same applies to #1 too)
3. JMS / kafka If this is a large application with separate processes helping with different tasks and these must be asynchronous then consider using a persistent queue or a stream like kafka.
All these approaches are feasible but you would need to look at your scenario and then apply one of these. Each of these come with a cost in-terms of resiliency / infra maintenance.
Maybe you will need some like this:
Server side:
Client side: