activemq topic demo

         这里仅仅记录下topic 模式的的消息情况:

     

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

import javax.jms.*;
import java.io.Serializable;

/**
 * Created by qiqiang on 2014/12/11.
 */
public class Sender {
    static ConnectionFactory factory; //连接工厂
    static Connection connection;//jms连接
    static Session session;//发送、接收线程
    static Destination destination;//消息目的地
    static MessageProducer producer;//消息发送者
    public static void main(String[] args) throws  Exception{
        try {
            factory = new ActiveMQConnectionFactory("tcp://localhost:61616");
            connection = factory.createConnection();
            connection.start();
            session = connection.createSession(true,Session.AUTO_ACKNOWLEDGE);
            Topic topic = session.createTopic("orderTopic");
            producer = session.createProducer(topic);
            producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
            for(int i=0;i<10;i++){
                ObjectMessage message =  session.createObjectMessage(new Order(i,"name"+i));
                producer.send(message);
                System.out.println("发送消息:"+i);
            }
            session.commit();

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            session.close();
            connection.close();;
        }
    }
}

class  Order implements Serializable {
    int i = 0;
    String name ;

    Order(int i, String name) {
        this.i = i;
        this.name = name;
    }

    @Override
    public String toString() {
        return "Order{" +
                "i=" + i +
                ", name='" + name + '\'' +
                '}';
    }
}
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * Created by qiqiang on 2014/12/11.
 */
public class Getter {
    public static void main(String[] args) {
        ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("failover:(tcp://localhost:61616)?initialReconnectDelay=10");
        try {
            Connection connection = factory.createConnection();
            connection.start();
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            Topic topic = session.createTopic("orderTopic");
            MessageConsumer consumer = session.createConsumer(topic);
            consumer.setMessageListener(new MessageListener() {
                public void onMessage(Message message) {
                    ObjectMessage tm = (ObjectMessage) message;
                    try {
                        System.out.println("Received message: " + tm.getObject());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }

}

相关推荐