JGroups

JGroups实现了组通讯的组件。

JGroups使用场合:

服务器集群

多服务器通讯

服务器复制

分布式缓存

更多JGroups信息可以参考whitesock的javaeye博客

无论是JGroups还是前面文章提到的ActiveMQ都是能够实现网络通信的。下面分享一个使用JGroups进行聊天的例子程序,大家感受下使用JGroups进行简单编程的例子

 

package ttstest;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.List;

import org.jgroups.JChannel;
import org.jgroups.Message;
import org.jgroups.ReceiverAdapter;
import org.jgroups.View;
import org.jgroups.util.Util;

public class SimpleChat {
	private JChannel channel;
	private List<String> state = new LinkedList<String>();
	private String userName = System.getProperty("user.name", "guchao");

	public void start() throws Exception {
	channel = new JChannel("./conf/udp.xml");
		channel.setReceiver(new ReceiverAdapter() {
			//回调方法,用来接收消息Message
			public void receive(Message msg) {
				System.out.println(msg.getSrc() + ": " + msg.getObject());
				synchronized(state) {
					state.add((String)msg.getObject());
				}
			}
			//回调方法,该方法能够得到新的view信息
			public void viewAccepted(View view) {
				System.out.println("view accepted: " + view);
			}

			public byte[] getState() {
				synchronized(state) {
					try {
						return Util.objectToByteBuffer(state);
					}
					catch(Exception e) {
						e.printStackTrace();
						return null;
					}
				}
			}

			@SuppressWarnings("unchecked")
			public void setState(byte[] new_state) {
				try {
					List<String> list=(List<String>)Util.objectFromByteBuffer(new_state);
					synchronized(state) {
						state.clear();
						state.addAll(list);
					}
					System.out.println("received state (" + list.size() + " messages in chat history):");
					for(String str: list) {
						System.out.println(str);
					}
				}
				catch(Exception e) {
					e.printStackTrace();
				}
			}
		});
		channel.connect("ChatCluster");
		channel.getState(null, 10000);

		//
		sendMessage();

		//
		channel.close();
	}

	private void sendMessage() throws Exception {
		boolean succeed = false;
		BufferedReader br = null;
		try {
			br = new BufferedReader(new InputStreamReader(System.in));
			while(true) {
				System.out.print(">");
				System.out.flush();
				String line = br.readLine();
				if(line != null && line.equals("exit")) {
					break;
				} else {
					Message msg = new Message(null, null, "[" + userName + "]" + line);
					channel.send(msg);
				}
			}
			succeed = true;
		} finally {
			if(br != null) {
				try {
					br.close();
				} catch (Exception e) {
					if(succeed) {
						throw e;
					}
				}
			}
		}
	}

	public static void main(String args[]) throws Exception {
		new SimpleChat().start();
	}
}

 

聪明的你应该可以发现,上面的这个例子通过jgroups发送消息的方式同步服务器的内存!!

你可能感兴趣的:(聊天,jgroups)