ActiveMQ的简单用法

消息生产者:

import org.apache.qpid.amqp_1_0.jms.impl.*;
import javax.jms.*;

/**
 * 生产者<br>
 * 
 */
class Publisher {

    public static void main(String[] args) throws Exception {

        String user = "admin";
        String password = "admin";
        String host = "localhost";
        int port = 5672;
        ConnectionFactoryImpl factory = new ConnectionFactoryImpl(host, port, user, password);
        Connection connection = factory.createConnection(user, password);
        connection.start();
        Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
        Destination dest = session.createQueue("vinces");
        MessageProducer producer = session.createProducer(dest);
        producer.setDeliveryMode(DeliveryMode.PERSISTENT);
        TextMessage msg = session.createTextMessage("测试的ActiveMQ消息 ");
        // 生产一个消息
        producer.send(msg);
        // 提交
        session.commit();
        System.out.println("发送成功!");
        // 关闭连接
        connection.close();
        System.exit(0);
    }

}

消息消费者:

import org.apache.qpid.amqp_1_0.jms.impl.*;
import javax.jms.*;

/**
 * 消费者 <br> 
 * 
 */
class Listener {

    public static void main(String []args) throws JMSException {

        String user = "admin";
        String password = "admin";
        String host = "localhost";
        int port = 5672;
        ConnectionFactoryImpl factory = new ConnectionFactoryImpl(host, port, user, password);
        Connection connection = factory.createConnection(user, password);
        connection.start();
        Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
        Destination dest =  session.createQueue("vinces");
        MessageConsumer consumer = session.createConsumer(dest);
        System.out.println("Waiting for messages...");
        while(true) {
            TextMessage message = (TextMessage) consumer.receive(1000);
            if(message != null){
                System.out.println(message.getText());
                if("exit".equals(message.getText())) {
                    System.out.println("exit");
                    connection.close();
                    System.exit(1);
                }
            }
        }
    }

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值