####Cometd介绍
> [CometD](http://cometd.org/)框架是一个已经存在了好几年的基于HTTP的事件驱动的通信解决方案,其版本2增加了对注解配置和WebSocket的支持。CometD框架提供了一个Java服务器端的部分和一个Java客户端的部分,以及基于JQuery和Dojo的JavaScript客户端库。CometD使用了一个被称作Bayeux的标准的通信协议,允许你激活消息确认、流程控制、同步以及集群等的某些扩展。
> CometD的事件驱动方法非常适合事件驱动的web开发这一新概念,和传统的桌面用户界面一样,所有的组件通信通过一个总线来发送通知和接收事件,因此所有的通信都是异步的。
! [](http://pic001.cnblogs.com/images/2011/24634/2011092717111753.gif)
####Cometd和DropWizard的结合
直接上代码,CometdBundle的run方法实现如下:
public void run(CometdConfigHolder configuration, Environment environment) throws Exception {
AbstractServerFactory svrFactory =(AbstractServerFactory)configuration.getServerFactory();
String rootPath =svrFactory.getJerseyRootPath();
if(!rootPath.endsWith("/")){
rootPath+="/";
}
rootPath=rootPath.replace("/*", "");
FilterHolder fconfig = environment.getApplicationContext().addFilter(CrossOriginFilter.class, rootPath+"cometd/*",null);
fconfig.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, "*");
Map<String,String> initParameters = new HashMap<>();
initParameters.put("timeout", "20000");
initParameters.put("interval", "0");
initParameters.put("maxInterval", "10000");
initParameters.put("maxLazyTimeout", "5000");
initParameters.put("long-polling.multiSessionInterval", "2000");
initParameters.put("ws.cometdURLMapping", rootPath+"cometd/*");
initParameters.put("transports","org.cometd.websocket.server.JettyWebSocketTransport,org.cometd.server.transport.AsyncJSONTransport");
if(cometdConfig!=null){
initParameters.putAll(cometdConfig.initParameters);
}
ServletHolder holder = environment.getApplicationContext().addServlet(AnnotationCometDServlet.class, rootPath+"cometd/*");
holder.setInitOrder(1);
holder.setInitParameters(initParameters);
ServletHolder initHolder = environment.getApplicationContext().addServlet(BayeuxStartupServlet.class, rootPath+"initcometd"+System.currentTimeMillis());
initHolder.setInitOrder(2);
//websocket相关的注册
try {
WebSocketUpgradeFilter wsfilter = WebSocketUpgradeFilter.configureContext(environment.getApplicationContext());
wsfilter.getFactory().getPolicy().setIdleTimeout(5000);
} catch (ServletException e) {
throw new RuntimeException(e);
}
}