ActiveMQ实例

来源:互联网 发布:知柏地黄丸能治失眠吗 编辑:程序博客网 时间:2024/05/24 04:51

ProducerTool.java用于发送消息:

[java] view plaincopyprint?
  1. import javax.jms.Connection;     
  2. import javax.jms.DeliveryMode;     
  3. import javax.jms.Destination;     
  4. import javax.jms.JMSException;     
  5. import javax.jms.MessageProducer;     
  6. import javax.jms.Session;     
  7. import javax.jms.TextMessage;     
  8.     
  9. import org.apache.activemq.ActiveMQConnection;     
  10. import org.apache.activemq.ActiveMQConnectionFactory;     
  11.     
  12. public class ProducerTool {     
  13.     
  14.     private String user = ActiveMQConnection.DEFAULT_USER;     
  15.     
  16.     private String password = ActiveMQConnection.DEFAULT_PASSWORD;     
  17.     
  18.     private String url = ActiveMQConnection.DEFAULT_BROKER_URL;     
  19.     
  20.     private String subject = "TOOL.DEFAULT";     
  21.     
  22.     private Destination destination = null;     
  23.     
  24.     private Connection connection = null;     
  25.     
  26.     private Session session = null;     
  27.     
  28.     private MessageProducer producer = null;     
  29.     
  30.     // 初始化     
  31.     private void initialize() throws JMSException, Exception {     
  32.         ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(     
  33.                 user, password, url);     
  34.         connection = connectionFactory.createConnection();     
  35.         session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);     
  36.         destination = session.createQueue(subject);     
  37.         producer = session.createProducer(destination);     
  38.         producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);     
  39.     }     
  40.     
  41.     // 发送消息     
  42.     public void produceMessage(String message) throws JMSException, Exception {     
  43.         initialize();     
  44.         TextMessage msg = session.createTextMessage(message);     
  45.         connection.start();     
  46.         System.out.println("Producer:->Sending message: " + message);     
  47.         producer.send(msg);     
  48.         System.out.println("Producer:->Message sent complete!");     
  49.     }     
  50.     
  51.     // 关闭连接     
  52.     public void close() throws JMSException {     
  53.         System.out.println("Producer:->Closing connection");     
  54.         if (producer != null)     
  55.             producer.close();     
  56.         if (session != null)     
  57.             session.close();     
  58.         if (connection != null)     
  59.             connection.close();     
  60.     }     
  61. }      

ConsumerTool.java用于接受消息,我用的是基于消息监听的机制,需要实现MessageListener接口,这个接口有个onMessage方法,当接受到消息的时候会自动调用这个函数对消息进行处理。

[java] view plaincopyprint?
  1. import javax.jms.Connection;     
  2. import javax.jms.Destination;     
  3. import javax.jms.JMSException;     
  4. import javax.jms.MessageConsumer;     
  5. import javax.jms.Session;     
  6. import javax.jms.MessageListener;     
  7. import javax.jms.Message;     
  8. import javax.jms.TextMessage;     
  9.     
  10. import org.apache.activemq.ActiveMQConnection;     
  11. import org.apache.activemq.ActiveMQConnectionFactory;     
  12.     
  13. public class ConsumerTool implements MessageListener {     
  14.     
  15.     private String user = ActiveMQConnection.DEFAULT_USER;     
  16.     
  17.     private String password = ActiveMQConnection.DEFAULT_PASSWORD;     
  18.     
  19.     private String url = ActiveMQConnection.DEFAULT_BROKER_URL;     
  20.     
  21.     private String subject = "TOOL.DEFAULT";     
  22.     
  23.     private Destination destination = null;     
  24.     
  25.     private Connection connection = null;     
  26.     
  27.     private Session session = null;     
  28.     
  29.     private MessageConsumer consumer = null;     
  30.     
  31.     // 初始化     
  32.     private void initialize() throws JMSException, Exception {  
  33.      //连接工厂是用户创建连接的对象,这里使用的是ActiveMQ的ActiveMQConnectionFactory根据url,username和password创建连接工厂。  
  34.         ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(     
  35.                 user, password, url);   
  36.         //连接工厂创建一个jms connection  
  37.         connection = connectionFactory.createConnection();     
  38.         //是生产和消费的一个单线程上下文。会话用于创建消息的生产者,消费者和消息。会话提供了一个事务性的上下文。  
  39.         session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);  //不支持事务   
  40.         //目的地是客户用来指定他生产消息的目标还有他消费消息的来源的对象,两种消息传递方式:点对点和发布/订阅  
  41.         destination = session.createQueue(subject);   
  42.         //会话创建消息的生产者将消息发送到目的地  
  43.         consumer = session.createConsumer(destination);     
  44.              
  45.     }     
  46.     
  47.     // 消费消息     
  48.     public void consumeMessage() throws JMSException, Exception {     
  49.         initialize();     
  50.         connection.start();     
  51.              
  52.         System.out.println("Consumer:->Begin listening...");     
  53.         // 开始监听     
  54.         consumer.setMessageListener(this);     
  55.         // Message message = consumer.receive();     
  56.     }     
  57.     
  58.     // 关闭连接     
  59.     public void close() throws JMSException {     
  60.         System.out.println("Consumer:->Closing connection");     
  61.         if (consumer != null)     
  62.             consumer.close();     
  63.         if (session != null)     
  64.             session.close();     
  65.         if (connection != null)     
  66.             connection.close();     
  67.     }     
  68.     
  69.     // 消息处理函数     
  70.     public void onMessage(Message message) {     
  71.         try {     
  72.             if (message instanceof TextMessage) {     
  73.                 TextMessage txtMsg = (TextMessage) message;     
  74.                 String msg = txtMsg.getText();     
  75.                 System.out.println("Consumer:->Received: " + msg);     
  76.             } else {     
  77.                 System.out.println("Consumer:->Received: " + message);     
  78.             }     
  79.         } catch (JMSException e) {     
  80.             // TODO Auto-generated catch block     
  81.             e.printStackTrace();     
  82.         }     
  83.     }     
  84. }   

 

如果想主动的去接受消息,而不用消息监听的话,把consumer.setMessageListener(this)改为Message message = consumer.receive(),手动去调用MessageConsumer的receive方法即可。

下面是测试类Test.java:

[java] view plaincopyprint?
  1. import javax.jms.JMSException;     
  2. mport org.apache.activemq.ActiveMQConnection;  
  3.     
  4. public class Test {     
  5.     
  6.     /**   
  7.      * @param args   
  8.      */    
  9.     public static void main(String[] args) throws JMSException, Exception {     
  10.        
  11.      // TODO Auto-generated method stub     
  12.         ConsumerTool consumer = new ConsumerTool();     
  13.         ProducerTool producer = new ProducerTool();    
  14.         System.out.println(ActiveMQConnection.DEFAULT_BROKER_URL+"------------");  
  15.         // 开始监听     
  16.         consumer.consumeMessage();     
  17.              
  18.         // 延时500毫秒之后发送消息     
  19.         Thread.sleep(500);     
  20.         producer.produceMessage("Hello, world!");     
  21.         producer.close();     
  22.              
  23.         // 延时500毫秒之后停止接受消息     
  24.         Thread.sleep(500);     
  25.         consumer.close();     
  26.     }     
  27. }     

原创粉丝点击