JMS HelloWorld实现

  接着上一讲的内容,首先引入一个新的概念:JMS提供者

  要使用Java消息服务,你必须要有一个JMS提供者,管理会话和队列。既有开源的提供者也有专有的提供者。

开源的提供者包括:

Apache ActiveMQ

JBoss 社区所研发的 HornetQ

Joram

Coridan的MantaRay

The OpenJMS Group的OpenJMS

专有的提供者包括:

BEA的BEA WebLogic Server JMS

TIBCO Software的EMS

GigaSpaces Technologies的GigaSpaces

Softwired 2006的iBus

IONA Technologies的IONA JMS

SeeBeyond的IQManager(2005年8月被Sun Microsystems并购)

webMethods的JMS+ -

my-channels的Nirvana

Sonic Software的SonicMQ

SwiftMQ的SwiftMQ

IBM的WebSphere MQ

==================================================================================

这里,我们主要以apache开源的activemq作为提供者,来管理会话和队列......主要包含如下的内容:

    activemq的部署(Linux和windows两种,二选一即可)  ,

    ActiveMQ 点对点消息实现 ,

   ActiveMQ 发布-订阅消息模式实现

一. activemq运行环境的搭建(这里以windows为例):

      1. 官网地址:http://activemq.apache.org

      2.开发包及源码下载地址:http://activemq.apache.org/activemq-5111-release.html

     3.下载好安装包后,直接减压,进入到bin目录,有个win32和win64这种,根据电脑的版本进行启动即可.....

     4.启动后,在浏览器中输入ActiveMQ 服务启动地址:http://127.0.0.1:8161/admin/

        默认用户名/密码:admin/admin,能够顺利登录上来,说明已经部署完成..........

    需要注意的是:安装mq之前需要先配置java环境变量........

二.ActiveMQ 点对点消息实现:

    参照下图,可以很快实现代码的编写:

      

    1. 第一节:直接 Receive 方式:       

    创建消息生产者:

package com.lxz.activemq;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;

/**
 * 消息生产者  ---点对点消息实现
 * @author lxz
 *
 */
public class JMSProducer {
    
    private static final String USERNAME = ActiveMQConnectionFactory.DEFAULT_USER; //默认用户名
    private static final String PASSWORD=ActiveMQConnectionFactory.DEFAULT_PASSWORD;// 默认密码
    private static final String BROKEURL=ActiveMQConnectionFactory.DEFAULT_BROKER_URL; //默认访问地址
    private static final int SENDNUM=10; //发送消息的数量

    public static void main(String[] args) {
        
        ConnectionFactory connectionFactory; //连接工厂
        Connection connection = null; //连接
        Session session; //会话  接收或者发送消息的队列
        Destination destination;//消息目的地
        MessageProducer messageProducer; //消息生产者
        
        //实例化连接工厂
 connectionFactory = new ActiveMQConnectionFactory(JMSProducer.USERNAME, JMSProducer.PASSWORD, JMSProducer.BROKEURL);
        try {
            connection = connectionFactory.createConnection(); //创建连接
            session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE); //创建session
            destination = session.createQueue("FirstQueue1"); //创建队列
            messageProducer = session.createProducer(destination); //创建消息生产者

            sendMessage(session, messageProducer); //发送消息
            session.commit(); //提交事务
            
        } catch (JMSException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            if(connection!=null){
                try {
                    connection.close();
                } catch (JMSException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
    
    
    /**
     * 发送消息
     * @param session
     * @param messageProducer
     */
    public static void sendMessage(Session session,MessageProducer messageProducer){
        for(int i=0;i<SENDNUM;i++){
            try {
                TextMessage textMessage = session.createTextMessage("ActiveMQ发送的消息:"+i);
                messageProducer.send(textMessage);
            } catch (JMSException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

}
 

创建消息消费者:

package com.lxz.activemq;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;

/**
 * 消息消费者
 * @author lxz
 *
 */
public class JMSConsumer {

      private static final String USERNAME=ActiveMQConnectionFactory.DEFAULT_USER;//默认用户名
      private static final String PASSWORD=ActiveMQConnectionFactory.DEFAULT_PASSWORD; //默认密码
      private static final String BROKEURL=ActiveMQConnectionFactory.DEFAULT_BROKER_URL; //默认的连接地址
    
      public static void main(String[] args) {
        
          ConnectionFactory connectionFactory; //连接工厂
          Connection connection; //连接
          Session session; //会话  接受或者发送消息的一个线程
          Destination destination; //消息目的地
          MessageConsumer messageConsumer; //消息消费者
          
          //实例化连接工厂
  connectionFactory = new ActiveMQConnectionFactory(JMSConsumer.USERNAME, JMSConsumer.PASSWORD, JMSConsumer.BROKEURL);
          try {
              connection = connectionFactory.createConnection(); //通过连接工厂获取连接
              connection.start(); //开启连接
              session = connection.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE); //创建session
              destination = session.createQueue("FirstQueue1"); //创建连接的消息队列
              messageConsumer = session.createConsumer(destination); //创建消息消费者
              while(true){
                 TextMessage textMessage = (TextMessage) messageConsumer.receive(100000);
                 if(textMessage!=null){
                     System.out.println("收到的消息:"+textMessage.getText());
                 }else{
                     break;
                 }
              }
              
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }
}

    2. 第二节:使用 Listener 监听方式

 消息生产者:

package com.lxz.activemq;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;

/**
 * 消息生产者  ---点对点消息实现
 * @author lxz
 *
 */
public class JMSProducer {
    
    private static final String USERNAME = ActiveMQConnectionFactory.DEFAULT_USER; //默认用户名
    private static final String PASSWORD=ActiveMQConnectionFactory.DEFAULT_PASSWORD;// 默认密码
    private static final String BROKEURL=ActiveMQConnectionFactory.DEFAULT_BROKER_URL; //默认访问地址
    private static final int SENDNUM=10; //发送消息的数量

    public static void main(String[] args) {
        
        ConnectionFactory connectionFactory; //连接工厂
        Connection connection = null; //连接
        Session session; //会话  接收或者发送消息的队列
        Destination destination;//消息目的地
        MessageProducer messageProducer; //消息生产者
        
        //实例化连接工厂
 connectionFactory = new ActiveMQConnectionFactory(JMSProducer.USERNAME, JMSProducer.PASSWORD, JMSProducer.BROKEURL);
        try {
            connection = connectionFactory.createConnection(); //创建连接
            session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE); //创建session
            destination = session.createQueue("FirstQueue1"); //创建队列
            messageProducer = session.createProducer(destination); //创建消息生产者

            sendMessage(session, messageProducer); //发送消息
            session.commit(); //提交事务
            
        } catch (JMSException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            if(connection!=null){
                try {
                    connection.close();
                } catch (JMSException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
    
    
    /**
     * 发送消息
     * @param session
     * @param messageProducer
     */
    public static void sendMessage(Session session,MessageProducer messageProducer){
        for(int i=0;i<SENDNUM;i++){
            try {
                TextMessage textMessage = session.createTextMessage("ActiveMQ发送的消息:"+i);
                messageProducer.send(textMessage);
            } catch (JMSException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

}

 定义一个监听器:

package com.lxz.listener;

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

/**
 * 消息监听  
 * @author admin
 *
 */
public class Listener implements MessageListener {

    public void onMessage(Message message) {
        // TODO Auto-generated method stub
        try {
            System.out.println("接收到的消息:"+((TextMessage)message).getText());
        } catch (JMSException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    
}
 

  消息消费者:

package com.lxz.activemq;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.Session;

import org.apache.activemq.ActiveMQConnectionFactory;

import com.lxz.listener.Listener;

/**
 * 消息消费者
 * @author lxz
 *
 */
public class JMSConsumer_2 {

      private static final String USERNAME=ActiveMQConnectionFactory.DEFAULT_USER;//默认用户名
      private static final String PASSWORD=ActiveMQConnectionFactory.DEFAULT_PASSWORD; //默认密码
      private static final String BROKEURL=ActiveMQConnectionFactory.DEFAULT_BROKER_URL; //默认的连接地址
    
      public static void main(String[] args) {
        
          ConnectionFactory connectionFactory; //连接工厂
          Connection connection; //连接
          Session session; //会话  接受或者发送消息的一个线程
          Destination destination; //消息目的地
          MessageConsumer messageConsumer; //消息消费者
          
          //实例化连接工厂
   connectionFactory = new ActiveMQConnectionFactory(JMSConsumer_2.USERNAME, JMSConsumer_2.PASSWORD, JMSConsumer_2.BROKEURL);
          try {
              connection = connectionFactory.createConnection(); //通过连接工厂获取连接
              connection.start(); //开启连接
              session = connection.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE); //创建session
              destination = session.createQueue("FirstQueue1"); //创建连接的消息队列
              messageConsumer = session.createConsumer(destination); //创建消息消费者
              messageConsumer.setMessageListener(new Listener()); //注册消息监听
              
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }
}
 

三 发布-订阅消息模式实现:

    订阅者(定义两个订阅者):

           订阅者一:    

package com.lxz.activemq2;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;

import com.lxz.listener.Listener;
import com.lxz.listener2.Listener2;

/**
 * 消息消费者 ----消息订阅者一
 * @author lxz
 *
 */
public class JMSConsumer_1 {

      private static final String USERNAME=ActiveMQConnectionFactory.DEFAULT_USER;//默认用户名
      private static final String PASSWORD=ActiveMQConnectionFactory.DEFAULT_PASSWORD; //默认密码
      private static final String BROKEURL=ActiveMQConnectionFactory.DEFAULT_BROKER_URL; //默认的连接地址
    
      public static void main(String[] args) {
        
          ConnectionFactory connectionFactory; //连接工厂
          Connection connection; //连接
          Session session; //会话  接受或者发送消息的一个线程
          Destination destination; //消息目的地
          MessageConsumer messageConsumer; //消息消费者
          
          //实例化连接工厂
          connectionFactory = new ActiveMQConnectionFactory(JMSConsumer_1.USERNAME, JMSConsumer_1.PASSWORD, JMSConsumer_1.BROKEURL);
          try {
              connection = connectionFactory.createConnection(); //通过连接工厂获取连接
              connection.start(); //开启连接
              session = connection.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE); //创建session
              destination = session.createTopic("FirstTopic1"); //创建连接的消息队列
              messageConsumer = session.createConsumer(destination); //创建消息消费者
              messageConsumer.setMessageListener(new Listener2()); //注册消息监听
              
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }
}
 

          订阅者二:

package com.lxz.activemq2;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.Session;

import org.apache.activemq.ActiveMQConnectionFactory;

import com.lxz.listener2.Listener;


/**
 * 消息消费者  ----消息订阅者二
 * @author lxz
 *
 */
public class JMSConsumer_2 {

      private static final String USERNAME=ActiveMQConnectionFactory.DEFAULT_USER;//默认用户名
      private static final String PASSWORD=ActiveMQConnectionFactory.DEFAULT_PASSWORD; //默认密码
      private static final String BROKEURL=ActiveMQConnectionFactory.DEFAULT_BROKER_URL; //默认的连接地址
    
      public static void main(String[] args) {
        
          ConnectionFactory connectionFactory; //连接工厂
          Connection connection; //连接
          Session session; //会话  接受或者发送消息的一个线程
          Destination destination; //消息目的地
          MessageConsumer messageConsumer; //消息消费者
          
          //实例化连接工厂
          connectionFactory = new ActiveMQConnectionFactory(JMSConsumer_2.USERNAME, JMSConsumer_2.PASSWORD, JMSConsumer_2.BROKEURL);
          try {
              connection = connectionFactory.createConnection(); //通过连接工厂获取连接
              connection.start(); //开启连接
              session = connection.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE); //创建session
              //destination = session.createQueue("FirstQueue1"); //创建连接的消息队列
              destination = session.createTopic("FirstTopic1"); //创建连接的消息队列
              messageConsumer = session.createConsumer(destination); //创建消息消费者
              messageConsumer.setMessageListener(new Listener()); //注册消息监听
              
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }
}

   自定义两个监听器:

   监听器一: 

package com.lxz.listener2;

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

/**
 * 消息监听  ---订阅者一
 * @author admin
 *
 */
public class Listener implements MessageListener {

    public void onMessage(Message message) {
        // TODO Auto-generated method stub
        try {
            System.out.println("接收到订阅者一的消息:"+((TextMessage)message).getText());
        } catch (JMSException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }   
}

监听器二:

    

package com.lxz.listener2;

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

/**
 * 消息监听  ---订阅者二
 * @author admin
 *
 */
public class Listener2 implements MessageListener {

    public void onMessage(Message message) {
        // TODO Auto-generated method stub
        try {
            System.out.println("接收到订阅者二的消息:"+((TextMessage)message).getText());
        } catch (JMSException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    
}

    消息发布者:

package com.lxz.activemq2;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;

/**
 * 消息生产者 ---消息发布者
 * @author lxz
 *
 */
public class JMSProducer {
    
    private static final String USERNAME=ActiveMQConnectionFactory.DEFAULT_USER;  //默认用户名
    private static final String PASSWORD=ActiveMQConnectionFactory.DEFAULT_PASSWORD;  //默认密码
    private static final String BROKEURL=ActiveMQConnectionFactory.DEFAULT_BROKER_URL; //默认的连接地址
    private static final int SENDNUM =10;//发送的消息数

    public static void main(String[] args) {
        
        ConnectionFactory connectFactory; //连接工厂
        Connection connection = null; //连接
        Session session; //会话   接收或者发送消息的线程
        Destination destination; //消息目的地
        MessageProducer messageProducer; //消息生产者
        
        //实例化连接工厂
 connectFactory = new ActiveMQConnectionFactory(JMSProducer.USERNAME, JMSProducer.PASSWORD, JMSProducer.BROKEURL);
        
        try {
            connection = connectFactory.createConnection(); //通过连接工厂获取连接
            connection.start(); //开启连接
            session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); //创建session 
            destination = session.createTopic("FirstTopic1"); //创建消息队列
            messageProducer = session.createProducer(destination); //创建消息生产者
            sendMessage(session, messageProducer); //发送消息
            session.commit(); //提交事务
        } catch (JMSException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            if(connection!=null){
                try {
                    connection.close();
                } catch (JMSException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
    
    /**
     * 发送消息
     * @param session
     * @param messageProducer
     */
    public static void sendMessage(Session session,MessageProducer messageProducer){
        for(int i=0;i<JMSProducer.SENDNUM;i++){
            try {
                TextMessage textMessage =session.createTextMessage("ActiveMQ发送的消息"+i);
                System.out.println("发送的消息:"+"activeMQ发布的消息"+i);
                messageProducer.send(textMessage);
            } catch (JMSException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

}
 

注意:在eclipse中创建java工程的时候,需要引入一个activemq-all-5.11.1.jar文件

到此......activemq就讲完了........如有不足,欢迎指正......

 

   

  

 
 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值