1 package ch02.chat; 2 3 4 import javax.jms.Connection; 5 import javax.jms.ConnectionFactory; 6 import javax.jms.Destination; 7 import javax.jms.MapMessage; 8 import javax.jms.MessageProducer; 9 import javax.jms.Session; 10 11 import org.apache.activemq.ActiveMQConnectionFactory; 12 13 class Send 14 { 15 public static void main(String[] args) throws Exception { 16 ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(); 17 18 Connection connection = (Connection) connectionFactory.createConnection(); 19 connection.start(); 20 21 Session session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE); 22 Destination destination = session.createQueue("my-queue"); 23 24 MessageProducer producer = session.createProducer(destination); 25 for(int i=0; i<3; i++) { 26 27 MapMessage message=session.createMapMessage(); 28 message.setLong("age",15 ); 29 message.setString("name", "zhangsa"); 30 Thread.sleep(1000); 31 //通过消息生产者发出消息 32 producer.send(message); 33 } 34 session.commit(); 35 session.close(); 36 connection.close(); 37 } 38 39 40 41 }
1.发送客户端,发送3个key-value的信息、
用localhost:8161查看message的内容:
3.开启消费进程
1 package ch02.chat; 2 3 import java.sql.Connection; 4 5 import javax.jms.ConnectionFactory; 6 import javax.jms.Destination; 7 import javax.jms.JMSException; 8 import javax.jms.MapMessage; 9 import javax.jms.Message; 10 import javax.jms.MessageConsumer; 11 import javax.jms.MessageListener; 12 import javax.jms.Session; 13 14 import org.apache.activemq.ActiveMQConnectionFactory; 15 16 public class Receive { 17 18 public static void main(String[] args) throws JMSException { 19 // TODO Auto-generated method stub 20 ConnectionFactory conFactory=new ActiveMQConnectionFactory(); 21 javax.jms.Connection con=conFactory.createConnection(); 22 con.start(); 23 final Session session=con.createSession(false,Session.AUTO_ACKNOWLEDGE ); 24 Destination des=session.createQueue("my-queue"); 25 MessageConsumer consumer=session.createConsumer(des); 26 consumer.setMessageListener(new MessageListener(){ 27 28 @Override 29 public void onMessage(Message m) { 30 // TODO Auto-generated method stub 31 if(m instanceof MapMessage){ 32 MapMessage mm=(MapMessage)m; 33 try { 34 System.out.println(mm.getLong("age")); 35 System.out.println(mm.getString("name")); 36 } catch (JMSException e) { 37 // TODO Auto-generated catch block 38 e.printStackTrace(); 39 } 40 41 } 42 43 } 44 45 46 47 }); 48 49 50 } 51 52 }
查看信息没了,哈哈哈