In a standard cluster scenario, the node is sent through a packet to the well-agreed multicast IP address: port, which establishes the communication. Use a TCP plug, for example.
"Simulating a clustered scene with a servlet"
"1. Connect the @serverendpoint"
"What the nodes do."
Ws://localhost:8080/cluster/clusternodesocket/clusternode1/query
Uri uri = new uri ("ws", "localhost:8080", path, NULL, NULL);
Connect the WebSocket
This.session = Containerprovider.getwebsocketcontainer ()
. Connecttoserver (this, URI);
"What the server does."
2 Public voidOnOpen (Session session, @PathParam ("NodeId") String nodeId)3 {8Clustermessage message =NewClustermessage (NodeId, "Joined the cluster."); One //notifies all nodes that there is a new node join because this is happening in OnOpen, that is, a proxy on the terminal connection. A byte[] bytes =clusternodeendpoint.tobytearray (message); - for(Session node:ClusterNodeEndpoint.nodes) - //Send Bytebuffer the node.getbasicremote (). Sendbinary (Bytebuffer.wrap (bytes)); A ClusterNodeEndpoint.nodes.add (session); at}
"2.Servlet is responsible for routing requests and receiving messages, and the server is responsible for passing messages to other nodes"
"Node processing GET Request"
2 protected voiddoget (httpservletrequest request, httpservletresponse response)3 throwsservletexception, IOException4 {6 //constructs a message to be sent to the node7Clustermessage message =NewClustermessage ( This. NodeId,8"Request:{ip:\" "+ request.getremoteaddr () +9"\", querystring:\ "" + request.getquerystring () + "\"} ");Ten One //using the serialization mechanism to send messages A Try(OutputStream output = This. Session.getbasicremote (). Getsendstream (); -ObjectOutputStream stream =NewObjectOutputStream (output)) - { the stream.writeobject (message); - } -Response.getwriter (). Append ("OK"); -}
"Node receives message"
1 @OnMessage2 Public voidonMessage (InputStream input)3 {4 Try(ObjectInputStream stream =NewObjectInputStream (input))5 {6Clustermessage message =(Clustermessage) stream.readobject ();7System.out.println ("INFO Node" + This. NodeId +8"): Message received from cluster; node = "+9Message.getnodeid () + ", message =" +message.getmessage ());Ten } One Catch(IOException |classnotfoundexception e) A { - e.printstacktrace (); - } the}
"Server passes to other node messages"
1 @OnMessage2 Public voidOnMessage (Session session,byte[] message)3 {4 Try5 {6 for(Session node:ClusterNodeEndpoint.nodes)7 {8 //send messages to other nodes (messages from the current node)9 if(Node! =session) One node.getbasicremote (). Sendbinary (bytebuffer.wrap (message)); A } - } - Catch(IOException e) the { -System.err.println ("error:exception when handling message on server"); - e.printstacktrace (); - } +}
Use WebSocket to help applications cluster inter-node communication