1 18 19 package org.apache.activemq.spring; 20 21 import org.apache.commons.logging.Log; 22 import org.apache.commons.logging.LogFactory; 23 import org.springframework.jms.core.JmsTemplate; 24 25 import javax.jms.Connection ; 26 import javax.jms.ConnectionFactory ; 27 import javax.jms.Destination ; 28 import javax.jms.JMSException ; 29 import javax.jms.Message ; 30 import javax.jms.MessageConsumer ; 31 import javax.jms.MessageListener ; 32 import javax.jms.Session ; 33 34 public class SpringConsumer extends ConsumerBean implements MessageListener { 35 private static final Log log = LogFactory.getLog(SpringConsumer.class); 36 37 private JmsTemplate template; 38 private String myId = "foo"; 39 private Destination destination; 40 private Connection connection; 41 private Session session; 42 private MessageConsumer consumer; 43 44 public void start() throws JMSException { 45 String selector = "next = '" + myId + "'"; 46 47 try { 48 ConnectionFactory factory = template.getConnectionFactory(); 49 connection = factory.createConnection(); 50 51 synchronized (connection) { 54 if (connection.getClientID() == null) { 55 connection.setClientID(myId); 56 } 57 } 58 59 connection.start(); 60 61 session = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE); 62 consumer = session.createConsumer(destination, selector, false); 63 consumer.setMessageListener(this); 64 } 65 catch (JMSException ex) { 66 log.error("", ex); 67 throw ex; 68 } 69 } 70 71 72 public void stop() throws JMSException { 73 if( consumer!=null ) 74 consumer.close(); 75 if( session!=null ) 76 session.close(); 77 if( connection!=null ) 78 connection.close(); 79 } 80 81 public void onMessage(Message message) { 82 super.onMessage(message); 83 try { 84 message.acknowledge(); 85 } 86 catch (JMSException e) { 87 log.error("Failed to acknowledge: " + e, e); 88 } 89 } 90 91 public Destination getDestination() { 94 return destination; 95 } 96 97 public void setDestination(Destination destination) { 98 this.destination = destination; 99 } 100 101 public String getMyId() { 102 return myId; 103 } 104 105 public void setMyId(String myId) { 106 this.myId = myId; 107 } 108 109 public JmsTemplate getTemplate() { 110 return template; 111 } 112 113 public void setTemplate(JmsTemplate template) { 114 this.template = template; 115 } 116 } 117 | Popular Tags |