日期:2014-05-20 浏览次数:20780 次
public class MessageDispatcher {
private final Logger log = LoggerFactory.getLogger(MessageDispatcher.class);
public MessageDispatcher() {
messageQueue = new ArrayBlockingQueue<String>(2048);
}
private BlockingQueue<String> messageQueue;
public int putMessage(String packet) {
try {
messageQueue.put(packet);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return 0;
}
public String getMessage() {
try {
String packet = messageQueue.take();
log.info("get message queue size:"+messageQueue.size());
return packet;
} catch (InterruptedException e) {
log.error("get message error:" + e.getMessage());
}
return null;
}
}
public class ServiceSkeleton {
private final Logger LOG = LoggerFactory.getLogger(ServiceSkeleton.class);
private MessageThread messageThread;
public ServiceSkeleton(MessageDispatcher dispatcher) {
this.dispatcher = dispatcher;
}
public void start() {
messageThread=new MessageThread(dispatcher,this);
messageThread.start();
}
public void onMessage(String packet) {
System.out.println(packet);
}
private MessageDispatcher dispatcher;
}
class MessageThread extends Thread {
private final Logger LOG = LoggerFactory.getLogger(MessageThread.class);
boolean runFlag=true;
public MessageThread(MessageDispatcher dispatcher,ServiceSkeleton sk){
this.dispatcher=dispatcher;
this.sk=sk;
}
MessageDispatcher dispatcher;
ServiceSkeleton sk;
synchronized void setRunFlag(boolean flag){
this.runFlag=flag;
}
@Override
public void run() {
while (true) {
LOG.info("get message from dispatcher!");
String msg = dispatcher.getMessage();
if (null != msg) {
try{
sk.onMessage(msg);
}catch(Exception e){
LOG.error("handler message error({})",e.getMessage());
}
}
}
}
}