【Java.JMS】一个简单的JMS实例

转载自:http://blog.csdn.net/robinjwong/article/details/38820259

选择ActiveMQ。


建立一个简单的Maven工程,pom.xml如下:

[html] view plain copy

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">  
      <modelVersion>4.0.0</modelVersion>  
      
      <groupId>com.gof</groupId>  
      <artifactId>jms-test</artifactId>  
      <version>0.0.1-SNAPSHOT</version>  
      <packaging>jar</packaging>  
      
      <name>jms-test</name>  
      <url>http://maven.apache.org</url>  
      
      <properties>  
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>  
      </properties>  
      
      <dependencies>  
        <dependency>  
          <groupId>junit</groupId>  
          <artifactId>junit</artifactId>  
          <version>3.8.1</version>  
          <scope>test</scope>  
        </dependency>  
          
        <!-- Add by WXB -->  
        <dependency>  
          <groupId>org.apache.activemq</groupId>  
          <artifactId>activemq-client</artifactId>  
          <version>5.10.0</version>  
        </dependency>  
          
      </dependencies>  
    </project>  


创建测试类:

[java] view plain copy

    package com.gof.jms.test;  
      
    import javax.jms.Connection;  
    import javax.jms.ConnectionFactory;  
    import javax.jms.DeliveryMode;  
    import javax.jms.Destination;  
    import javax.jms.Message;  
    import javax.jms.MessageConsumer;  
    import javax.jms.MessageProducer;  
    import javax.jms.Session;  
    import javax.jms.TextMessage;  
      
    import org.apache.activemq.ActiveMQConnectionFactory;  
      
    public class SimpleMessageSendandReceiveApp {  
        public static final String user = "system";  
        public static final String password = "manager";  
        public static final String url = "tcp://localhost:61616";  
        public static final String queueName = "test_queue";  
        public static final String messageBody = "Hello JMS!";  
        public static final boolean transacted = false;  
        public static final boolean persistent = false;  
          
        public static void main(String[] args){  
            Connection connection = null;  
            Session session = null;  
              
            try{  
                // create the connection  
                ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(user, password, url);  
                connection = connectionFactory.createConnection();  
                connection.start();  
                  
                // create the session  
                session = connection.createSession(transacted, Session.AUTO_ACKNOWLEDGE);  
                Destination destination = session.createQueue(queueName);  
                  
                // create the producer  
                MessageProducer producer = session.createProducer(destination);  
                if (persistent){  
                    producer.setDeliveryMode(DeliveryMode.PERSISTENT);  
                }else{  
                    producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);  
                }  
                  
                // create text message  
                Message message = session.createTextMessage(messageBody);  
                  
                // send the message  
                producer.send(message);  
                System.out.println("Send message: " + ((TextMessage)message).getText());  
                  
                // create the consumer  
                MessageConsumer consumer = session.createConsumer(destination);  
                // blocking till receive the message  
                Message recvMessage = consumer.receive();  
                System.out.println("Receive message: " + ((TextMessage)recvMessage).getText());  
                  
            }catch (Exception e){  
                e.printStackTrace();  
            }finally{  
                try{  
                    // close session and connection  
                    if (session != null){  
                        session.close();  
                    }  
                    if (connection != null){  
                        connection.close();  
                    }  
                }catch (Exception e){  
                    e.printStackTrace();  
                }  
            }  
        }  
    }<span style="font-family:SimSun;font-size:10px;">  
    </span>  


开始测试:

启动ActiveMQ,在admin页面(http://localhost:8161/admin)中创建名为test_queue的Queue:


分步运行程序,当调用:

[java] view plain copy

    producer.send(message);  

可以看到ActiveMQ接收到了这个消息:

同时也可以看到该Queue当前的Active Producer:


当调用:

[java] view plain copy

    consumer.receive();  

可以看到该消息被消费掉:


在控制台中,可以看到输出的结果:

[html] view plain copy

    Send message: Hello JMS!  
    Receive message: Hello JMS!
ActiveMQ安装 : 1.下载:http://activemq.apache.org/download.html 最新Windows版本 2.配置jdk环境,解压ActiveMQ到本地 3.启动ActiveMQ服务器: 32位机 : 直接运行\bin\win32\activemq.bat 64位机 : 直接运行\bin\win64\activemq.bat 4.打开ActiveMQ消息管理后台系统 http://localhost:8161/admin/ 参考文章为 : HelloWorld : http://blog.csdn.net/baggio7095586/article/details/5708519 进阶 :http://haohaoxuexi.iteye.com/blog/1893038 helloworld阶段 : 一个发送消息的程序,一个接收消息的程序..实现最简单JMS交流... 监听器阶段 : ⑴MessageListener,最简单的监听器..只是拿来监听接收信息的 ⑵SessionAwareMessageListener,有个session的参数..可以拿来对接收到的信息再做响应.. ⑶MessageListenerAdapter,将消息委托交给一个普通的java类来处理.. 转化器阶段 : 实现MessageConverter接口来转换JMS对象与java对象.. 其实在使用MessageListenerAdapter时,Spring默认为我们提供了SimpleMessageConverter转换器.. 事务(无代码): 在Spring整合JMS的应用中,如果我们要进行本地的事务管理的话非常简单,只需要在定义对应的消息监听容器时指定其sessionTransacted属性为true,如: <bean id="jmsContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer"> <property name="connectionFactory" ref="connectionFactory" /> <property name="destination" ref="queueDestination" /> <property name="messageListener" ref="consumerMessageListener" /> <property name="sessionTransacted" value="true"/> </bean> 该属性值默认为false,这样JMS在进行消息监听的时候就会进行事务控制,当在接收消息时监听器执行失败时JMS就会对接收到的消息进行回滚, 对于SessionAwareMessageListener在接收到消息后发送一个返回消息时也处于同一事务下,但是对于其他操作如数据库访问等将不属于该事务控制。 数据库跟JMS挂钩的事务先别理..
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值