博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
EJB3.0定时发送jms(发布/定阅)方式
阅读量:4143 次
发布时间:2019-05-25

本文共 5412 字,大约阅读时间需要 18 分钟。

 

EJB3.0定时发送jms(发布/定阅)方式  

介绍:

定时器分为两种:single-action Timer(单动定时器)和interval  Timer(间隔定时器)。

为了使用定时服务,1.enterprise bean必须实现javax.ejb.TimedObject接口,该接口定义了一个回调方法,ejbTimeout().

package javax.ejb;

public interface TimedObject{

           public void ejbTimeout(Timer timer);

}

2.在EJB3.0中,还可以使用@javax.ejb.Timeout注解来指定回调方法。此方法必须返回void,并接受一个javax.ejb.Timer类型的参数。

开发者有3种获得TimerService对象的可用方式。

1.通过EJBContext获得TimerService实例。

2.使用JNDI API查找到TimerService对象,从而能够访问到定时器服务。

3.还可以借助于依赖注入 获得TimerService对象,

@Resource  javax.ejb.TimerService    timerService。

TimeService接口为enterprise bean 访问EJB容器的定时服务提供 了支持,利用它可以创建新的定时器,列出已有的定时器。

优点:

1.EJB定时器服务提供的任务调度语义与平台无关。

2.EJB定时器服务允许开发者通过编程实现定时器的定义和设定。

3.最后,同Flux或Quartz相比,EJB定时器服务提供了标准化接口。

缺点:

1.EJB规范不支持在部署描述符或Annotation注释中声明Timer间隔。

2.EJB定时器服务中的定时器的使用不够灵活。定时器API仅能处理单位为毫秒的时间。如果能够依据小时、日、月方式指定定时器的行为,则EJB定时器服务的使用也将变的更加容易。

package ejb_jms;

import javax.jms.JMSException;

public interface HelloWorld {

      public void sendMessage(String time)throws JMSException;

}

@Stateless

@Remote( { HelloWorld.class })

@Local( { HelloWorld.class })

@RemoteBinding(jndiBinding = "byc:/ejb3/helloworld")

public class HelloWorldBean implements HelloWorld {

    @Resource(mappedName = "byc:/ejb3/MyAccountBean")

    MyAccount Rcount;  

    public void sendMessage(String time) throws JMSException {

        System.out.println("sendMessage====");

        Hashtable ht = new Hashtable();

        ht.put("java.naming.factory.initial",

                "org.jnp.interfaces.NamingContextFactory");

        ht.put("java.naming.factory.url.pkgs", "org.jboss.naming");

        ht.put("java.naming.provider.url", "jnp://localhost:1099");

        ConnectionFactory cf = null;

        Topic topic = null;

        TopicConnectionFactory tcf = null;

        TopicConnection tc = null;

        TopicSession ts = null;

        TopicPublisher tp = null;

        ObjectMessage mmsg = null;

        try {

            Context ctx = new InitialContext(ht);

            //找到工厂类

            cf = (ConnectionFactory) ctx.lookup("ConnectionFactory");

            tcf = (TopicConnectionFactory) cf;

            topic = (Topic) ctx.lookup("topic/IPMACTopic");

            //获取连接

            tc = tcf.createTopicConnection();

            ts = tc.createTopicSession(false, TopicSession.AUTO_ACKNOWLEDGE);

            //获取发布相当与session

            tp = ts.createPublisher(topic);

        } catch (NamingException e1) {

            // TODO Auto-generated catch block

            System.out.println("sendMessage ==发送消息创建失败====");

        } catch (Exception e1) {

            // TODO Auto-generated catch block

            System.out.println("sendMessage ==发送消息创建失败===2=");

        }

        // 在这里发消息

        try {

            // 消息类别共三种

            mmsg = ts.createObjectMessage();

            // 设置MapMassge的主题

            mmsg.setJMSType("example");//主题

            //内容

            mmsg.setObject(time);

            // 发布JMS消息;

            tp.send(mmsg);

            System.out.println("发送成功====");

        } catch (JMSException e) {

       

            System.out.println("sendMessage ==jms发送消息失败====");

            e.getStackTrace();

        } finally {

            //关闭资源

            if (tp != null) {

                tp.close();

            }

            if (ts != null) {

                ts.close();

            }

            if (tc != null) {

                tc.close();

            }

        }

    }

}

@Stateless

@Remote( { TimerService.class })

@Local( { TimerService.class })

@RemoteBinding(jndiBinding = "byc:/ejb3/TimerServiceBean")

public class TimerServiceBean implements TimerService {

    @EJB(beanName = "HelloWorldBean")

    HelloWorld HelloWorldBean;

    private int count = 1;

    private @Resource

    SessionContext ctx;// 通过@Resource获取jndi上的SessionContext对象

    String name = "gaochong";

    public void scheduleTimer(long milliseconds) {

        count = 1;

        ctx.getTimerService().createTimer(

                new Date(new Date().getTime() + milliseconds), milliseconds,

                "大家好,这是我的第一个定时器");

    }

    @Timeout

    public void timeoutHandler(Timer timer) throws JMSException {

        System.out.println("---------------------");

        System.out.println("定时器事件发生");

        System.out.println("---------------------");

        if (count >= 5) {

            timer.cancel();// 如果定时器触发5次,便终止定时器

           

        }

        HelloWorldBean.sendMessage(name);

        count++;

    }

}

@MessageDriven(activationConfig = {

        @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Topic"),//javax.jms.Queue  类型

        @ActivationConfigProperty(propertyName = "destination", propertyValue = "topic/IPMACTopic") //位置

})

public class PrintBean implements MessageListener {

    public void onMessage(Message msg) {

        try {

            if (msg instanceof MapMessage) {

                System.out.println("MapMessage example....");

                MapMessage mmsg = (MapMessage) msg;

                String jmstype = null;

                jmstype = mmsg.getJMSType();

                if (jmstype != null && jmstype.equals("alarm_original")) {

                    System.out.println("JMSType:" + mmsg.getJMSType());

                    System.out.println("message:" + mmsg.getString("detail"));

                }

                else {

                    System.out.println(mmsg.getJMSType() + " is null");

                }

            }

            if (msg instanceof ObjectMessage) {

                System.out.println("ObjectMessage example....");

                ObjectMessage mmsg = (ObjectMessage) msg;

                String jmstype = null;

                jmstype = mmsg.getJMSType();

                if (jmstype != null && jmstype.equals("example")) {

                    long time = System.currentTimeMillis();

                    Object o = (String) mmsg.getObject();

                    System.out.println("接收...." + o.toString());

                }

            }

            if (msg instanceof MapMessage) {

                System.out.println("MapMessage example....");

            }

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

}

public class Test {

        public static void main(String args[]) throws NamingException {

                Properties props = new Properties();

        props.setProperty("java.naming.factory.initial",

                "org.jnp.interfaces.NamingContextFactory");

        props.setProperty("java.naming.provider.url", "localhost:1099");

        props.setProperty("java.naming.factory.url.pkgs", "org.jboss.naming");

        InitialContext ctx = new InitialContext(props);// 客户端和jboss运行在同一个jvm,不需要传入props

             HelloWorld helloworld = (HelloWorld) ctx.lookup("byc:/ejb3/helloworld");

             TimerService timer=(TimerService) ctx.lookup("byc:/ejb3/TimerServiceBean");

             timer.scheduleTimer(8000);

       }

}

转载地址:http://otbti.baihongyu.com/

你可能感兴趣的文章
vue项目打包后无法运行报错空白页面
查看>>
Vue 解决部署到服务器后或者build之后Element UI图标不显示问题(404错误)
查看>>
element-ui全局自定义主题
查看>>
facebook库runtime.js
查看>>
vue2.* 中 使用socket.io
查看>>
openlayers安装引用
查看>>
js报错显示subString/subStr is not a function
查看>>
高德地图js API实现鼠标悬浮于点标记时弹出信息窗体显示详情,点击点标记放大地图操作
查看>>
初始化VUE项目报错
查看>>
vue项目使用安装sass
查看>>
HTTP和HttpServletRequest 要点
查看>>
在osg场景中使用GLSL语言——一个例子
查看>>
laravel 修改api返回默认的异常处理
查看>>
laravel事务
查看>>
【JavaScript 教程】浏览器—History 对象
查看>>
这才是学习Vite2的正确姿势!
查看>>
7 个适用于所有前端开发人员的很棒API,你需要了解一下
查看>>
25个构建Web项目的HTML建议,你需要了解一下!
查看>>
【web素材】02-10款大气的购物商城网站模板
查看>>
6种方式实现JavaScript数组扁平化(flat)方法的总结
查看>>