JMS实现activeMq记录

JMS实现activeMq记录

1.从官网下载包:apache-activemq-5.11.1-bin.zip
解压,启动activemq后台服务,启动前需要先配置java环境变量
http://127.0.0.1:8161/admin 用户名和密码默认为:admin/admin
2.消息主要模式为点对点和发布与订阅两种模式.

第一种模式,点对点:

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.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
/**
 * 消息生产者
 * @author wy
 */
public class JMSProducer {

    private static final String USERNAME = ActiveMQConnection.DEFAULT_USER;
    private static final String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;
    private static final String BROKERURL = ActiveMQConnection.DEFAULT_BROKER_URL;
    private static final int SENDNUMBER = 10;

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ConnectionFactory connectionFactory;//连接工厂
        Connection connection = null;
        Session session;//消息线程
        Destination destination;//消息目的地
        MessageProducer messageProducer;//消息生产者 
        connectionFactory = new ActiveMQConnectionFactory(USERNAME, PASSWORD, BROKERURL);
        try {
            connection = connectionFactory.createConnection();
            connection.start();//启动连接
            session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);//创建session
            destination = session.createQueue("first_queue1");//创建消息队列
            messageProducer = session.createProducer(destination);//创建消息生产者
            sendMessage(session,messageProducer);
            session.commit();
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            if(connection!=null){
                try {
                    connection.close();
                } catch (JMSException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
    public static void sendMessage(Session session,MessageProducer messageProducer)throws Exception{
        for(int i=0;i<SENDNUMBER;i++){
            TextMessage message = session.createTextMessage("发送的消息:"+i);
            System.out.println("发送的消息:"+i);
            messageProducer.send(message);
        }
    }

}

以上是消息生产者来生成消息进入队列.然后看一下消息接收者(消息消费者).

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

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
/*
 * 消息消费者
 */
public class JMSConsumer {

    private static final String USERNAME = ActiveMQConnection.DEFAULT_USER;
    private static final String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;
    private static final String BROKERURL = ActiveMQConnection.DEFAULT_BROKER_URL;
    private static final int SENDNUMBER = 10;

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ConnectionFactory connectionFactory;//连接工厂
        Connection connection = null;
        Session session;//消息线程
        Destination destination;//消息目的地
        MessageConsumer messageConsumer;

        connectionFactory = new ActiveMQConnectionFactory(USERNAME, PASSWORD, BROKERURL);
        try {
            connection = connectionFactory.createConnection();
            connection.start();//启动连接
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);//创建session
            destination = session.createQueue("first_queue");//创建消息队列
            messageConsumer = session.createConsumer(destination);//创建消息消费者
            //======================方式1,普通接收消息模式==================//
            boolean flag = true;
            while(flag){
                TextMessage textMessage = (TextMessage)messageConsumer.receive(100000);
                if(textMessage != null){
                    System.out.println("收到的消息:"+textMessage.getText());
                }else {
                    flag = false;  //跳出循环
                }
            }
            //======================方式1==================//
            //======================方式2,监听接收消息模式,当前模式最常用==================//
            messageConsumer.setMessageListener(new Listener(){  
                  @Override  
                  public void onMessage(Message m) {  
                      TextMessage textMsg = (TextMessage) m;  
                      try {  
                          System.out.println(textMsg.getText());  
                      } catch (JMSException e) {  
                          e.printStackTrace();  
                       }  
                   }  

               });  
            //======================方式2==================//
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

第二种模式,订阅与发布模式:

可以想象成订阅报纸,先订阅报纸后,然后就会收到报纸,代码如下:

package 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.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
/*
 * 消息发布者
 */
public class JMSProducer {
    private static final String USERNAME = ActiveMQConnection.DEFAULT_USER;
    private static final String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;
    private static final String BROKERURL = ActiveMQConnection.DEFAULT_BROKER_URL;
    private static final int SENDNUMBER = 10;

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ConnectionFactory connectionFactory;//连接工厂
        Connection connection = null;
        Session session;//消息线程
        Destination destination;//消息目的地
        MessageProducer messageProducer;//消息生产者 
        connectionFactory = new ActiveMQConnectionFactory(USERNAME, PASSWORD, BROKERURL);
        try {
            connection = connectionFactory.createConnection();
            connection.start();//启动连接
            session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);//创建session
            destination = session.createTopic("first_topic");//发布消息
            messageProducer = session.createProducer(destination);//创建消息生产者
            sendMessage(session,messageProducer);
            session.commit();
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            if(connection!=null){
                try {
                    connection.close();
                } catch (JMSException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
    public static void sendMessage(Session session,MessageProducer messageProducer)throws Exception{
        for(int i=0;i<SENDNUMBER;i++){
            TextMessage message = session.createTextMessage("发布的消息:"+i);
            System.out.println("发布的消息:"+i);
            messageProducer.send(message);
        }
    }

}

以上代码是消息发布者,在执行发布者前,需要先执行以下代码,来订阅topic
订阅者1:

package activemq2;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
/*
 * 订阅者1
 */
public class JMSConsumer1 {

    private static final String USERNAME = ActiveMQConnection.DEFAULT_USER;
    private static final String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;
    private static final String BROKERURL = ActiveMQConnection.DEFAULT_BROKER_URL;

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ConnectionFactory connectionFactory;//连接工厂
        Connection connection = null;
        Session session;//消息线程
        MessageConsumer messageConsumer;
        connectionFactory = new ActiveMQConnectionFactory(USERNAME, PASSWORD, BROKERURL);
        try {
            connection = connectionFactory.createConnection();
            connection.start();//启动连接
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);//创建session
            Topic topic = session.createTopic("first_topic");//创建消息队列
            messageConsumer = session.createConsumer(topic);//创建消息消费者
            messageConsumer.setMessageListener(new Listener(){  
                          @Override  
                          public void onMessage(Message m) {  
                              TextMessage textMsg = (TextMessage) m;  
                              try {  
                                  System.out.println("订阅者1的:"+textMsg.getText());  
                              } catch (JMSException e) {  
                                  e.printStackTrace();  
                               }  
                           }  
                       });  

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

并同时运行订阅者2:

package activemq2;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
/*
 * 订阅者2
 */
public class JMSConsumer2 {

    private static final String USERNAME = ActiveMQConnection.DEFAULT_USER;
    private static final String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;
    private static final String BROKERURL = ActiveMQConnection.DEFAULT_BROKER_URL;

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ConnectionFactory connectionFactory;//连接工厂
        Connection connection = null;
        Session session;//消息线程
        MessageConsumer messageConsumer;
        connectionFactory = new ActiveMQConnectionFactory(USERNAME, PASSWORD, BROKERURL);
        try {
            connection = connectionFactory.createConnection();
            connection.start();//启动连接
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);//创建session
            Topic topic = session.createTopic("first_topic");//订阅标题
            messageConsumer = session.createConsumer(topic);//创建消息消费者
            messageConsumer.setMessageListener(new Listener(){  
                          @Override  
                          public void onMessage(Message m) {  
                              TextMessage textMsg = (TextMessage) m;  
                              try {  
                                  System.out.println("订阅者2的:"+textMsg.getText());  
                              } catch (JMSException e) {  
                                  e.printStackTrace();  
                               }  
                           }  
                       });  

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

运行两个订阅者之后运行消息发布者,然后两个消息订阅者监听便能收到发布的消息

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wangyue23com

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值