light-weight distributed messaging via JGroups

Tuesday, December 11, 2007 6:16
Posted in category Development

JGroups is a framework that provide seamless networking utilities for java/j2ee applications. As a light-weight alternative to JMS here is an example.


import org.jgroups.Channel;
import org.jgroups.JChannel;
import org.jgroups.Message;
import org.jgroups.blocks.GroupRequest;
import org.jgroups.blocks.MessageDispatcher;
import org.jgroups.blocks.RequestHandler;
import org.jgroups.util.RspList;

/**
* @author altuure
*/
public class MessageDispatcherTest implements RequestHandler {
/**instance count*/
public static final int THREAD_COUNT = 2;
/**jgroups config can use null or predefined config lke udp.xml*/
public static final String JGROUPS_PROPERTIES = null;

/**instance identifier*/
public final long RANDOM = Math.round(Math.random() * 1000);
/** messaging group**/
public static final String MESSAGE_DISPATCHER_TEST_GROUP
= "MessageDispatcherTestGroup";

public void start() throws Exception {
<u><em> Channel channel;
<font color="#333399"> channel = new JChannel(JGROUPS_PROPERTIES);// new channel
MessageDispatcher disp = new MessageDispatcher(channel, null, null, this);</font></em></u><font color="#333399">
// join group
<u> channel.connect(MESSAGE_DISPATCHER_TEST_GROUP);</u></font>
Thread.sleep(3000);
for (int i = 0; i < 30; i++) {
Thread.sleep(300);
System.out.println(RANDOM + ":Casting message #" + i);
RspList rsp_list =
<font color="#333399"> disp.castMessage(null,
new Message(null, null, new String(RANDOM + "Number #" + i)),
GroupRequest.GET_ALL, 0);</font>
System.out.println(RANDOM + ":Responses:\n" + rsp_list);
}
// close dispather
disp.stop();
// close networking
channel.close();

}

<font color="#333399">public Object handle(Message msg) {</font>

<font color="#333399">System.out.println(RANDOM + ":handle(): "
+ msg + ":" + (msg.getObject().toString()));
return new String("Success !" + RANDOM);
}</font>

public static void main(String[] args) {
try {

Runnable runnable = new Runnable() {
public void run() {
try {
new MessageDispatcherTest().start();
} catch (Exception e) {
e.printStackTrace();
}
}
};
// create multiple instance for test
for (int i = 0; i < THREAD_COUNT; i++)
new Thread(runnable).start();
}
catch (Exception e) {
System.err.println(e);
}
}
}

other posts for jgroups

Share and Enjoy:
  • Digg
  • del.icio.us
  • Netvouz
  • description
  • Wists
  • Technorati
  • YahooMyWeb
  • Furl
  • Slashdot
  • Google
  • Reddit
  • StumbleUpon
You can leave a response, or trackback from your own site.

Leave a Reply