ActiveMQ学习(二)Java应用

在Java中使用activemq需要在java工程中导入ActiveMQ需要的包

下载地址:http://mvnrepository.com/artifact/org.apache.activemq/activemq-all

一、发布消息

直接上例子了:
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * Created by sunp on 2017/2/6.
 */
public class sendMessage {
    //ActiveMQ连接工厂,JMS用它创建连接
    public static ConnectionFactory factory;
    //ActiveMQ连接:JMS客户端到JMS Provider的连接
    public static Connection connection;
    //Session:一个发送或接收消息的线程(会话)
    public static Session session;
    //Destination: 消息发送的目的地;消息发送给谁
    public static Destination destination;
    //MessageProducer消息生成者【发送者】
    public static MessageProducer producer;
    static{
        //创建工厂
        factory = new ActiveMQConnectionFactory(
                ActiveMQConnection.DEFAULT_USER,
                ActiveMQConnection.DEFAULT_PASSWORD,
                "failover://(tcp://127.0.0.1:61616,tcp://127.0.0.2:61616)"
        );
        try {
            //从工厂中获得连接对想
            connection = factory.createConnection();
            //启动
            connection.start();
            //获得操作连接
            session = connection.createSession(
                    Boolean.TRUE,
                    Session.AUTO_ACKNOWLEDGE
            );
            //创建Queue
            destination = session.createQueue("Test");
            //消息生产者
            producer = session.createProducer(destination);
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
            try{
                for (int i = 0; i < 20; i++) {
                    //创建消息
                    TextMessage message = session.createTextMessage("第"+(i+1)+"条消息");
                    //发送消息
                    producer.send(message);
                    System.out.println("已发送"+(i+1)+"条消息");
                    //提交
                    session.commit();
                }
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                try {
                    producer.close();
                    session.close();
                    connection.close();
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
    }
}

1.传输模式:

持久化传输(默认)
非持久化传输producer.setDeliveryMode(DeliveryMode.NoN_PERSISTENT)设置

区别:持久化传输,传输的消息会保存到磁盘中,即“存储转发“的方式,先存到磁盘中,然后转发给订阅者。而非持久化传输,不保存到磁盘。

2.确认模式:

确认模式用来指示会话如何确认收到消息,在使用Connection的createSession方法时需要指定此选项,在JMS的Session接口中包含下面四个选项
(1)AUTO_ACKNOWLEDGE = 1    自动确认
当会话从对 receive 的调用成功返回时,或在会话已调用的用于处理消息的消息侦听器成功返回时,会话会自动确认客户端的消息接收。
(2)CLIENT_ACKNOWLEDGE = 2    客户端手动确认
通过此确认模式,客户端通过调用消息的 acknowledge 方法确认已使用的消息。确认已使用的消息将确认该会话已使用的所有消息。
(3) DUPS_OK_ACKNOWLEDGE = 3    自动批量确认
此确认模式指示会话延迟确认消息的传送。这可能在 JMS 提供者失败的情况下导致传送某些重复消息,因此只有能允许重复消息的使用方才应使用此模式。
使用此模式可以通过最大限度地减少会话为防止重复所做的工作,从而减少会话开销
(4)SESSION_TRANSACTED = 0    事务提交并确认
如果会话是事务的则使用此模式,忽略设置的其他模式值。在事务开启之后,和session.commit()之前,所有消费的消息,要么全部正常确认,
要么全部redelivery。这种严谨性,通常在基于GROUP(消息分组)或者其他场景下特别适合。

二、接收消息

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * Created by sunp on 2017/2/6.
 */
public class receiverMessage{
    public static ConnectionFactory factory;
    public static Connection connection;
    public static Session session;
    public static Destination destination;
    public static MessageConsumer consumer;
    static{
        factory = new ActiveMQConnectionFactory(
                ActiveMQConnection.DEFAULT_USER,
                ActiveMQConnection.DEFAULT_PASSWORD,
                "failover://(tcp://192.168.1.169:61616,tcp://192.168.2.60:61616)"
        );
        try{
            connection = factory.createConnection();
            connection.start();
            session = connection.createSession(
                    Boolean.TRUE,
                    Session.AUTO_ACKNOWLEDGE
            );
            destination = session.createQueue("Test");
            consumer = session.createConsumer(destination);
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        while(true){
//            //第一种方法,同步接收数据
//            try {
//                TextMessage message = (TextMessage) consumer.receive((long)10000);
//                if(message!=null){
//                    System.out.println(message.getText());
//                    session.commit();
//                }
//            } catch (JMSException e) {
//                e.printStackTrace();
//            }
            //第二种方法,异步接收数据
            try {
                consumer.setMessageListener(new MessageListener() {
                    @Override
                    public void onMessage(Message message) {
                        if(message instanceof TextMessage){
                            try{
                                System.out.println(((TextMessage) message).getText());
                                session.commit();
                            }catch (Exception e){
                                e.printStackTrace();
                            }
                        }
                    }
                });
            } catch (JMSException e) {
                e.printStackTrace();
            }
            //注:千万不能用close()关闭连接否则消息接收不到
        }
     }
}
****(很重要)session如果设置事务,当接收并处理完消息后,一定要提交,告诉activemq成功接收消息。否则,activemq会认为没有消费者接受此消息,这个消息会一直存在。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值