JGroups
Documentation
Download
Misc
|
Application Programming Interface
|
The API of JGroups is very simple. The code is always the same, regardless of the protocol stack used.
To be able to send/receive messages, a channel has to be created.
The reliability of a channel is specified via XML, which then causes
the creation of the underlying protocol stack.
The example below creates a channel and sends/receives 1 message:
JChannel channel=new JChannel("/home/bela/udp.xml");
channel.setReceiver(new ReceiverAdapter() {
public void receive(Message msg) {
System.out.println("received msg from " + msg.getSrc() + ": " + msg.getObject());
}
});
channel.connect("MyCluster");
channel.send(new ObjectMessageSerializable(null, "hello world"));
channel.close();
The channel's configuration is defined in the constructor. In the sample code, we use an XML file
with an absolute path. If we use a relative path, then the file is looked up on the classpath.
The XML file contains a list of protocols to be used by the new channel.
To join a cluster, connect() is called. It returns when the member
has successfully joined the cluster named "MyCluster", or when it has created
a new cluster (if it is the first member).
Then a message is sent using the send() method. A message contains the receiver's address
(null = all cluster nodes) and a payload. In the example, the string "hello world" is set
to be the message's contents.
Since the message is sent to all members, the sender will also receive it.
This is done via the receive() callback, which was registered with the channel before.
Finally, the member closes the channel and thus leaves the cluster.
This results in a notification being sent to all members who are registered
for membership change notifications.
|
|
|