InterSenior Java Lead Interview Questions.(Advanced)-07
What are micro services?
Could you describe the ways micro services can communicate with one another?
Microservices can communicate using several methods as described below.
For more details on micro service inter communications please refer to my article:
Could you please explain Web Sockets and how are they used.
Web Socket Server.
import javax.websocket.OnMessage;
import javax.websocket.server.ServerEndpoint;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpointConfig;
@ServerEndpoint("/demo")
public class WebSocketServer {
@OnMessage
public String onMessage(String message) {
return "Server echoed: " + message;
}
public static void main(String[] args) {
// Server setup code goes here
// Typically, you would use an external server like Tomcat or Jetty to run this WebSocket server
}
}
WebSocket Client
import javax.websocket.ContainerProvider;
import javax.websocket.OnMessage;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;
import java.net.URI;
public class WebSocketClient {
@javax.websocket.ClientEndpoint
public static class ClientEndpoint {
@OnMessage
public void onMessage(String message) {
System.out.println("Received message: " + message);
}
}
public static void main(String[] args) {
try {
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
String uri = "ws://localhost:8080/demo"; // Replace with your server URI
Session session = container.connectToServer(ClientEndpoint.class, URI.create(uri));
session.getBasicRemote().sendText("Hello WebSocket");
// Wait to ensure the message is received before closing
Thread.sleep(1000);
session.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Thanks a lot for reading my content and helping me to write better and better by providing constant feedbacks and your claps. I really appreciate as single clap and all the people and my friends are showing interest in my content. I am really greatful. I will keep extending this list for more exhaustive interview preparation. Thanks for sharing.
A beautiful winter landscape for relaxation.