如何在DropWizard中支持Cometd


####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);
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值