Java Application Interaction with JGroups

    Today I want to talk about JGroups . This is a Java library for organizing group interaction between various Java processes. Applications using JGroups can:
    • Create and destroy groups
    • Join groups and leave them
    • Receive alerts about new group members
    • Send messages to a specific process or to all processes in a group
    The library is widely used, in particular in the JBoss application server, in the OSCache cache and in the Infinispan Grid platform.

    Here I will limit myself to the initial information and describe the creation of a simple group chat in Java.

    Beginning of work


    So, first you need to download JGroups. You can do this here: http://sourceforge.net/projects/javagroups/files/ . In writing this article, I used version 2.6.13.GA . Also, Apache Commons Logging, or something replacing it (for example, jcl-over-slf4j) is required for work. You can download here: http://commons.apache.org/downloads/download_logging.cgi .

    If you use Maven, you can add the JBoss repository:

    Copy Source | Copy HTML
    1.   jboss
    2.   jboss
    3.   http://repository.jboss.com/maven2
    4.   
    5.     false
    6.   
    and add depending:

    Copy Source | Copy HTML
    1.   jgroups
    2.   jgroups
    3.   2.6.13.GA
    4.  
    5.   commons-logging
    6.   commons-logging
    7.   1.1.1

    You may need to configure the network interface to work with multicast. On Linux, for this you need to add the appropriate route:

    route add -net 224.0.0.0 netmask 240.0.0.0 dev lo


    Initialization


    In order to create a channel, you need to create an object of the JChannel class , passing configuration parameters to it in the constructor. In the example in the configuration, I specify the address that should be used for the channel. A full list of options can be found in the documentation .

    JChannel channel = new JChannel( "UDP(bind_addr=127.0.0.1)" );

    Now you can connect to the cluster by calling JChannel # connect (). As a parameter, the name of the group is passed to it, you can choose any one that you like.

    channel.connect( "MyCluster" );

    Sending messages


    Messages in JGroups are represented by the Message class , which contains the sender address, recipient address, and data. Addresses are represented by objects of the Address class , and data is any serializable objects or just an array of bytes. For example, to create a message for the whole group containing a string, you can write:

    new Message( null, null, "Some content" )

    Here, the first parameter is the recipient, then the sender, and then the contents.

    To send a message, you need to call the JChannel # send method and pass the message to it as a parameter. For instance:

    channel.send( new Message( null, null, "Some content" ) )


    Message processing


    Now you need to write code to process messages arriving at the application. To do this, call the JChannel # setReceiver method, passing as an argument an object that implements the Receiver interface . For example, to simply print all received messages for printing, just write the following code:

    Copy Source | Copy HTML
    1. channel.setReceiver( new ReceiverAdapter(){
    2.  
    3.     @Override
    4.     public void receive( Message m ) {
    5.         System.out.println( m.getObject() );
    6.     }
    7.  
    8. } );
    Here, to reduce the amount of code, an object is inherited from the ReceiverAdapter class, which provides empty implementations of various methods of the Receiver interface. As you can see from the example, the receive method is used to process the message, into which the message is passed as a parameter.

    Simple chat


    Now you can put together a simple chat. He will send the group the lines received from the console and print the received lines to the console. Code example:

    Copy Source | Copy HTML
    1. import java.io.BufferedReader;
    2. import java.io.InputStreamReader;
    3.  
    4. import org.jgroups.JChannel;
    5. import org.jgroups.Message;
    6. import org.jgroups.ReceiverAdapter;
    7.  
    8. public class SimplestChat {
    9.  
    10.     public static void main( String[] args ) throws Exception {
    11.         JChannel channel = new JChannel( "UDP(bind_addr=127.0.0.1)" );
    12.         channel.setReceiver( new ReceiverAdapter() {
    13.  
    14.             @Override
    15.             public void receive( Message m ) {
    16.                 System.out.println( m.getObject() );
    17.             }
    18.  
    19.         } );
    20.         channel.connect( "MyCluster" ); // Подключаемся к группе
    21.  
    22.         /**
               * Цикл обработки команд с консоли
               */
    23.         BufferedReader in = new BufferedReader( new InputStreamReader( System.in ) );
    24.         while ( true ) {
    25.  
    26.             String line = in.readLine();
    27.  
    28.             if ( line.equalsIgnoreCase( "quit" ) || line.equalsIgnoreCase( "exit" ) ) {
    29.                 break;
    30.             }
    31.  
    32.             channel.send( new Message( null, null, line ) );
    33.         }
    34.  
    35.         channel.close(); // Отключаемся от группы по завершению работы
    36.     }
    37.  
    38. }
    When launched, this code should output something like:

      Nov 8, 2009 4:18:27 PM org.jgroups.JChannel init
      INFO: JGroups version: 2.6.13.GA
    

    What's next?


    Here I looked only at creating a channel and sending messages to a group. There were quite a few points aside: addressing, messages to a specific process and, most importantly, group management. Those who wish to familiarize themselves with them can take a look at the JGroups documentation: http://jgroups.org/ug.html .

    Also popular now: