我的编程空间,编程开发者的网络收藏夹
学习永远不晚

JMS in ejb3 call by

短信预约 -IT技能 免费直播动态提醒
省份

北京

  • 北京
  • 上海
  • 天津
  • 重庆
  • 河北
  • 山东
  • 辽宁
  • 黑龙江
  • 吉林
  • 甘肃
  • 青海
  • 河南
  • 江苏
  • 湖北
  • 湖南
  • 江西
  • 浙江
  • 广东
  • 云南
  • 福建
  • 海南
  • 山西
  • 四川
  • 陕西
  • 贵州
  • 安徽
  • 广西
  • 内蒙
  • 西藏
  • 新疆
  • 宁夏
  • 兵团
手机号立即预约

请填写图片验证码后获取短信验证码

看不清楚,换张图片

免费获取短信验证码

JMS in ejb3 call by

Purpose
This case will show how to create an MDB(message dirven bean) in EJB3 specification, and call it by two ways, one is use spring framework, another is call it directly. This case is aim to have a small view of JMS of EJB.
 
ENV and Container Setting
Here we use Jboss5.0GA, attention if you use Jboss4.X, it maybe have some different.
 
Setting of JMS in Jboss 5.0.GA
1.copy your database dirver jar to jboss lib if you will use database.
2.copy $JBOSS_HOME$/docs\examples\jca\mysql-ds.xml to server\default\deploy (if use mysql)
3.modify this mysql-ds.xml as:
<?xml version="1.0" encoding="UTF-8"?>

<!-- $Id: mysql-ds.xml 41017 2006-02-07 14:26:14Z acoliver $ -->
<!--    Datasource config for MySQL using 3.0.9 available from:
http://www.mysql.com/downloads/api-jdbc-stable.html
-->

<datasources>
    <local-tx-datasource>
        <jndi-name>MySqlDS</jndi-name>
        <connection-url>jdbc:mysql://localhost:3306/test</connection-url>
        <driver-class>com.mysql.jdbc.Driver</driver-class>
        <user-name>root</user-name>
        <password>root</password>
        <exception-sorter-class-name>org.jboss.resource.adapter.jdbc.vendor.MySQLExceptionSorter</exception-sorter-class-name>
        <!-- should only be used on drivers after 3.22.1 with "ping" support
        <valid-connection-checker-class-name>org.jboss.resource.adapter.jdbc.vendor.MySQLValidConnectionChecker</valid-connection-checker-class-name>
        
-->
        <!-- sql to call when connection is created
        <new-connection-sql>some arbitrary sql</new-connection-sql>
            
-->
        <!-- sql to call on an existing pooled connection when it is obtained from pool - MySQLValidConnectionChecker is preferred for newer drivers
        <check-valid-connection-sql>some arbitrary sql</check-valid-connection-sql>
            
-->

        <!-- corresponding type-mapping in the standardjbosscmp-jdbc.xml (optional) -->
        <metadata>
             <type-mapping>mySQL</type-mapping>
        </metadata>
    </local-tx-datasource>
</datasources>

4.copy $JBOSS_HOME$/docs/examples/jms/mysql-persistence-service.xml to server\default\deploy\messaging, and delete hsqldb-persistence-service.xml file.
Then edit it as:
<!-- Messaging Post Office MBean configuration
                =========================================
-->

     <mbean code="org.jboss.messaging.core.jmx.MessagingPostOfficeService"
            name="jboss.messaging:service=PostOffice"
            xmbean-dd="xmdesc/MessagingPostOffice-xmbean.xml">

            <depends optional-attribute-name="ServerPeer">jboss.messaging:service=ServerPeer</depends>

            <depends>jboss.jca:service=DataSourceBinding,name=MySqlDS</depends>

            <depends optional-attribute-name="TransactionManager">jboss:service=TransactionManager</depends>

            <!-- The name of the post office -->

            <attribute name="PostOfficeName">JMS post office</attribute>

            <!-- The datasource used by the post office to access it's binding information -->

            <attribute name="DataSource">java:/MySqlDS</attribute>

            <!-- If true will attempt to create tables and indexes on every start-up -->

            <!--<attribute name="CreateTablesOnStartup">true</attribute>-->

            <attribute name="SqlProperties"><![CDATA[
CREATE_POSTOFFICE_TABLE=CREATE TABLE JBM_POSTOFFICE (POSTOFFICE_NAME VARCHAR(255), NODE_ID INTEGER, QUEUE_NAME VARCHAR(255), COND VARCHAR(1023), SELECTOR VARCHAR(1023), CHANNEL_ID BIGINT, CLUSTERED CHAR(1), ALL_NODES CHAR(1), PRIMARY KEY(POSTOFFICE_NAME, NODE_ID, QUEUE_NAME)) ENGINE = INNODB
INSERT_BINDING=INSERT INTO JBM_POSTOFFICE (POSTOFFICE_NAME, NODE_ID, QUEUE_NAME, COND, SELECTOR, CHANNEL_ID, CLUSTERED, ALL_NODES) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
DELETE_BINDING=DELETE FROM JBM_POSTOFFICE WHERE POSTOFFICE_NAME=? AND NODE_ID=? AND QUEUE_NAME=?
LOAD_BINDINGS=SELECT QUEUE_NAME, COND, SELECTOR, CHANNEL_ID, CLUSTERED, ALL_NODES FROM JBM_POSTOFFICE WHERE POSTOFFICE_NAME=? AND NODE_ID=?
            ]]></attribute>

            <!-- This post office is non clustered. If you want a clustered post office then set to true -->
            
         <attribute name="Clustered">false</attribute>

            <!-- All the remaining properties only have to be specified if the post office is clustered.
                     You can safely comment them out if your post office is non clustered
-->

            <!-- The JGroups group name that the post office will use -->

         <!--    <attribute name="GroupName">${jboss.messaging.groupname:MessagingPostOffice}</attribute> -->

            <!-- Max time to wait for state to arrive when the post office joins the cluster -->

            <!--<attribute name="StateTimeout">30000</attribute>-->

            <!-- Max time to wait for a synchronous call to node members using the MessageDispatcher -->

            <!--<attribute name="CastTimeout">30000</attribute>-->
            
            <!-- Set this to true if you want failover of connections to occur when a node is shut down -->
            
            <!--<attribute name="FailoverOnNodeLeave">false</attribute>-->

            <!--<depends optional-attribute-name="ChannelFactoryName">jboss.jgroups:service=ChannelFactory</depends>-->
            <!--<attribute name="ControlChannelName">jbm-control</attribute>-->
            <!--<attribute name="DataChannelName">jbm-data</attribute>-->
            <!--<attribute name="ChannelPartitionName">${jboss.partition.name:DefaultPartition}-JMS</attribute>-->    
     </mbean>
 
5.If you want to use spring jms, you should edit file destinations-service.xml like this:
<?xml version="1.0" encoding="UTF-8"?>

  <!--
    Messaging Destinations deployment descriptor. $Id:
    destinations-service.xml 81998 2008-12-03 06:46:29Z
    scott.stark@jboss.org $
  
-->

<server>

  <!--
    The Default Dead Letter Queue. This destination is a dependency of an
    EJB MDB container. SpringJMSServer
  
-->

  <mbean code="org.jboss.jms.server.destination.QueueService" name="jboss.messaging.destination:service=Queue,name=DLQ"
    xmbean-dd="xmdesc/Queue-xmbean.xml">
    <depends optional-attribute-name="ServerPeer">
      jboss.messaging:service=ServerPeer</depends>
    <depends>jboss.messaging:service=PostOffice
    </depends>
  </mbean>

  <!--
            The Default Expiry Queue.
    
-->

  <mbean code="org.jboss.jms.server.destination.QueueService"
    name="jboss.messaging.destination:service=Queue,name=ExpiryQueue"
    xmbean-dd="xmdesc/Queue-xmbean.xml">
    <depends optional-attribute-name="ServerPeer">
      jboss.messaging:service=ServerPeer</depends>
    <depends>jboss.messaging:service=PostOffice
    </depends>
  </mbean>

  <!-- add by daniel zhou 2009-07-21 -->
  <mbean code="org.jboss.jms.server.destination.QueueService"
    name="jboss.messaging.destination:service=Queue,name=SpringJMSServer"
    xmbean-dd="xmdesc/Queue-xmbean.xml">
    <depends optional-attribute-name="ServerPeer">
      jboss.messaging:service=ServerPeer</depends>
    <depends>jboss.messaging:service=PostOffice
    </depends>
  </mbean>

</server>
 
Mian Code
 
MDB Part in EJB3
In ejb3 is more easier than ejb2.1 in MDB create and description, as you know the main reason is annotation from JDK5.
 
package jms;

import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;


@MessageDriven(activationConfig = {
    //Message type
    @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue"),
    //Destination of Message
    @ActivationConfigProperty(propertyName = "destination", propertyValue = "queue/SpringJMSServer")
    })
public class MessageReceive implements MessageListener {

  
  public MessageReceive() {
    // TODO Auto-generated constructor stub
  }

  
  public void onMessage(Message message) {
    //tm
    TextMessage tm = (TextMessage) message;

    //out
    try {
      System.out.println("Get text:"+tm.getText());
    } catch (JMSException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }

}
 
Spring part
 
xml file
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
  xmlns:jms="http://www.springframework.org/schema/jms" xmlns:sec="http://www.springframework.org/schema/security"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
    http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms.xsd
    http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-2.0.2.xsd">

  <bean id="jndiTemplate" class="org.springframework.jndi.JndiTemplate">
    <property name="environment">
      <props>
        <prop key="java.naming.factory.initial">org.jnp.interfaces.NamingContextFactory</prop>
        <prop key="java.naming.provider.url">localhost:1099</prop>
        <prop key="java.naming.factory.url.pkgs">org.jboss.naming</prop>
      </props>
    </property>
  </bean>
  <bean id="jmsQueueConnectionFactory" class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiTemplate">
      <ref bean="jndiTemplate" />
    </property>
    <property name="jndiName">
      <value>ConnectionFactory</value>
    </property>
  </bean>
  <bean id="destination" class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiTemplate">
      <ref bean="jndiTemplate" />
    </property>
    <property name="jndiName">
      <value>queue/SpringJMSServer</value>
    </property>
  </bean>
  <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate102">
    <property name="connectionFactory">
      <ref bean="jmsQueueConnectionFactory" />
    </property>
    <property name="defaultDestination">
      <ref bean="destination" />
    </property>
    <property name="receiveTimeout">
      <value>30000</value>
    </property>
  </bean>
  <bean id="jmsSender" class="jms.send.JMSSender">
    <property name="jmsTemplate">
      <ref bean="jmsTemplate" />
    </property>
  </bean>
    
    
</beans>
 
Bean
package jms.send;

import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import javax.jms.TextMessage;


public class JMSSender {

  private JmsTemplate jmsTemplate;

  
  public JMSSender() {

  }

  public void sendMessage(final String message) {
    jmsTemplate.send(new MessageCreator() {
      public Message createMessage(Session session) throws JMSException {
        TextMessage text = session.createTextMessage();
        text.setText(message);
        return text;
      }
    });
  }

  
  public JmsTemplate getJmsTemplate() {
    return jmsTemplate;
  }

  
  public void setJmsTemplate(JmsTemplate jmsTemplate) {
    this.jmsTemplate = jmsTemplate;
  }

}
 
Test class

package jms.test;

import java.util.Properties;

import javax.jms.JMSException;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.TextMessage;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import jms.send.JMSSender;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;




public class JMSTest {

  
  public static void main(String[] args) {
    //call by spring    
    JMSTest.sendMessageBySpringBean();

    //call directly
    JMSTest.sendMessageDriectly();
    
  }

  
  public static void sendMessageDriectly(){
    QueueConnection conn=null;
    QueueSender sender=null;
    QueueSession sess=null;
    Queue queue=null;
    
    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");
    try {
      InitialContext ctx=new InitialContext(props);
        
      //get connection factory
      QueueConnectionFactory factory=(QueueConnectionFactory) ctx.lookup("ConnectionFactory");
        
      //use connection factory create JMS connection
      conn=factory.createQueueConnection();
        
      //use JMS create Session
      sess=conn.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE);
        
      //get the jndi
      queue=(Queue) ctx.lookup("queue/SpringJMSServer");
    
      //create message publisher
      sender=sess.createSender(queue);
        
      //create message
      TextMessage msg=sess.createTextMessage("hello kids,this is daniel's message bean。");
        
      //publish message
      sender.send(msg);
      sess.close();
        
      //end massage
      System.out.println("Message have been send, you can see them in jboss console");
    } catch (NamingException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (JMSException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
    
  
  public static void     sendMessageBySpringBean() {
    System.out.println("Class loader initialize start...");
    ApplicationContext app = new ClassPathXmlApplicationContext(
        "applicationContext.xml");
    JMSSender jmsSender = (JMSSender) app.getBean("jmsSender");
    System.out.println("Class loader initialize end...");
    System.out.println("Send message start...");
    for (int index = 0; index < 10; index++) {
      jmsSender.sendMessage("This is " + index + "time to say:hello jms!");
    }

    System.out.println("Send message end...");
  }
}
 
Attention in Spring
In spring, you should import lib jars about JMS, such as  commons-logging.jar
,jmscommon.jar and attention because we use jboss here, so you should import which client jars, this is important point! Of course, beside them, spring.jar must be included, don't forget it!
 
If not, you can run spring and use MDB smoothly, if you still could not deal with it, contact me by msn:danni-505@hotmail.com
 
Source DownLoad

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

JMS in ejb3 call by

下载Word文档到电脑,方便收藏和打印~

下载Word文档

猜你喜欢

JMS in ejb3 call by

PurposeThis case will show how to create an MDB(message dirven bean) in EJB3 specification, and call it by two ways, one
2023-01-31

编程热搜

  • Python 学习之路 - Python
    一、安装Python34Windows在Python官网(https://www.python.org/downloads/)下载安装包并安装。Python的默认安装路径是:C:\Python34配置环境变量:【右键计算机】--》【属性】-
    Python 学习之路 - Python
  • chatgpt的中文全称是什么
    chatgpt的中文全称是生成型预训练变换模型。ChatGPT是什么ChatGPT是美国人工智能研究实验室OpenAI开发的一种全新聊天机器人模型,它能够通过学习和理解人类的语言来进行对话,还能根据聊天的上下文进行互动,并协助人类完成一系列
    chatgpt的中文全称是什么
  • C/C++中extern函数使用详解
  • C/C++可变参数的使用
    可变参数的使用方法远远不止以下几种,不过在C,C++中使用可变参数时要小心,在使用printf()等函数时传入的参数个数一定不能比前面的格式化字符串中的’%’符号个数少,否则会产生访问越界,运气不好的话还会导致程序崩溃
    C/C++可变参数的使用
  • css样式文件该放在哪里
  • php中数组下标必须是连续的吗
  • Python 3 教程
    Python 3 教程 Python 的 3.0 版本,常被称为 Python 3000,或简称 Py3k。相对于 Python 的早期版本,这是一个较大的升级。为了不带入过多的累赘,Python 3.0 在设计的时候没有考虑向下兼容。 Python
    Python 3 教程
  • Python pip包管理
    一、前言    在Python中, 安装第三方模块是通过 setuptools 这个工具完成的。 Python有两个封装了 setuptools的包管理工具: easy_install  和  pip , 目前官方推荐使用 pip。    
    Python pip包管理
  • ubuntu如何重新编译内核
  • 改善Java代码之慎用java动态编译

目录