// JMSCommunicationThread @Override protected void createProducersAndConsumers() throws Exception { final String configuration = model.getConfigurationName(); // Write (if allowed) and also read the client topic if (model.isWriteAllowed()) client_producer = createProducer(Preferences.getJMS_AlarmClientTopic(configuration)); else client_producer = null; client_consumer = createConsumer(Preferences.getJMS_AlarmClientTopic(configuration)); // Read messages from server server_consumer = createConsumer(Preferences.getJMS_AlarmServerTopic(configuration)); // Handle MapMessages final MessageListener message_listener = new MessageListener() { @Override public void onMessage(final Message message) { if (message instanceof MapMessage) handleMapMessage((MapMessage) message); else Activator.getLogger() .log(Level.WARNING, "Message type {0} not handled", message.getClass().getName()); } }; client_consumer.setMessageListener(message_listener); server_consumer.setMessageListener(message_listener); }
public void init( Connection connection, String queue, boolean isTopic, MessageListener mlisten, boolean isActive) { try { // Session: 一个发送或接收消息的线程 session = connection.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE); if (isTopic) { destination = session.createTopic(queue); } else { destination = session.createQueue(queue); } consumer = session.createConsumer(destination); if (isActive) { System.out.println(queue); LogSys.nodeLogger.info("创建一个主动方式获取消息的Receiver:" + queue); } else { if (mlisten == null) consumer.setMessageListener(this); else consumer.setMessageListener(mlisten); } } catch (JMSException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
public static void main(String[] args) throws Exception { try { Context context = init(); ConnectionFactory connectionFactory = (ConnectionFactory) context.lookup("net4j.jms.ConnectionFactory"); // $NON-NLS-1$ Destination destination = (Destination) context.lookup("StockTopic"); // $NON-NLS-1$ Connection connection = connectionFactory.createConnection(); Session session = connection.createSession(true, 0); MessageProducer publisher = session.createProducer(destination); MessageConsumer subscriber1 = session.createConsumer(destination); MessageConsumer subscriber2 = session.createConsumer(destination); subscriber1.setMessageListener(new MessageLogger("subscriber1")); // $NON-NLS-1$ subscriber2.setMessageListener(new MessageLogger("subscriber2")); // $NON-NLS-1$ connection.start(); publisher.send(session.createObjectMessage("Message 1")); // $NON-NLS-1$ publisher.send(session.createObjectMessage("Message 2")); // $NON-NLS-1$ publisher.send(session.createObjectMessage("Message 3")); // $NON-NLS-1$ publisher.send(session.createObjectMessage("Message 4")); // $NON-NLS-1$ session.commit(); } finally { ConcurrencyUtil.sleep(500); Server.INSTANCE.deactivate(); } }
/** * Create a MessageConsumer for the given JMS Session, registering a MessageListener for the * specified listener. * * @param session the JMS Session to work on * @return the MessageConsumer * @throws JMSException if thrown by JMS methods * @see #executeListener */ protected MessageConsumer createListenerConsumer(final Session session) throws JMSException { Destination destination = getDestination(); if (destination == null) { destination = resolveDestinationName(session, getDestinationName()); } MessageConsumer consumer = createConsumer(session, destination); if (this.taskExecutor != null) { consumer.setMessageListener( new MessageListener() { public void onMessage(final Message message) { taskExecutor.execute( new Runnable() { public void run() { processMessage(message, session); } }); } }); } else { consumer.setMessageListener( new MessageListener() { public void onMessage(Message message) { processMessage(message, session); } }); } return consumer; }
public void testRun() { // http://pookey.co.uk/wordpress/archives/74-playing-with-activemq-using-maven // http://java.sun.com/developer/technicalArticles/Ecommerce/jms/index.html String brokerURL = "tcp://localhost:61616"; ConnectionFactory factory; Connection connection; Session session; MessageProducer producer; final String fedoraAppEmailQueue = FedoraAppConstants.JMS_ECTD_RESULTS_Q; String string_1 = "/home/chet/batch_space/codu/ectd/logs/codu.ectd.april-08-2011_17:15:36-297.txt"; // ingest // report String string_2 = "/home/chet/batch_space/codu/ectd/logs/codu.ectd.april-08-2011_17:15:36-297.csv"; // pid // report try { factory = new ActiveMQConnectionFactory(brokerURL); connection = factory.createConnection(); connection.start(); session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); System.out.println("\n\n** session transactions is set to :" + session.getTransacted()); // send message Destination destination = session.createQueue(fedoraAppEmailQueue); producer = session.createProducer(destination); System.out.println("Creating Message "); Message message = session.createTextMessage(string_1 + "\n" + string_2 + "\n"); producer.send(message); connection.close(); // consume message connection = factory.createConnection(); connection.start(); session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); destination = session.createQueue(fedoraAppEmailQueue); MessageConsumer consumer = session.createConsumer(destination); consumer.setMessageListener(null); consumer.setMessageListener(new ActiveMQListener()); for (int i = 1; i < 10000000; i++) { System.out.println("looping"); } } catch (Exception e) { System.out.println("Exception: " + e.getMessage()); } } // testRun
/* * http://blog.itpub.net/10742815/viewspace-580334/ */ public static void main(String[] args) throws Exception { ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); Connection connection = factory.createConnection(); connection.start(); // 消息发送到这个Queue Queue queue = new ActiveMQQueue("testQueue"); // 消息回复到这个Queue Queue replyQueue = new ActiveMQQueue("replyQueue"); final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); // 创建一个消息,并设置它的JMSReplyTo为replyQueue。 Message message = session.createTextMessage("Andy"); message.setJMSReplyTo(replyQueue); MessageProducer producer = session.createProducer(queue); producer.send(message); // 消息的接收者 MessageConsumer comsumer = session.createConsumer(queue); comsumer.setMessageListener( new MessageListener() { public void onMessage(Message m) { try { // 创建一个新的MessageProducer来发送一个回复消息。 MessageProducer producer = session.createProducer(m.getJMSReplyTo()); producer.send(session.createTextMessage("Hello " + ((TextMessage) m).getText())); } catch (JMSException e1) { e1.printStackTrace(); } } }); // 这个接收者用来接收回复的消息 MessageConsumer comsumer2 = session.createConsumer(replyQueue); comsumer2.setMessageListener( new MessageListener() { public void onMessage(Message m) { try { System.out.println(((TextMessage) m).getText()); } catch (JMSException e) { e.printStackTrace(); } } }); }
public static void main(String[] args) { try { Context ctx = new InitialContext(); ConnectionFactory factory = (ConnectionFactory) ctx.lookup("ConnectionFactory"); Queue queue = (Queue) ctx.lookup("inbound"); Connection con = factory.createConnection(); final Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); final MessageConsumer consumer = session.createConsumer(queue); consumer.setMessageListener( new MessageListener() { @Override public void onMessage(Message message) { final String type; try { type = message.getStringProperty("type"); if (type != null && type.equals("xml")) { System.out.println(((TextMessage) message).getText()); } } catch (JMSException e) { e.printStackTrace(); } } }); con.start(); } catch (Exception e) { e.printStackTrace(); } }
protected void activate(ComponentContext componentContext) { String serverId = clusterTrackingService.getCurrentServerId(); clusterTrackingServiceImpl = (ClusterTrackingServiceImpl) clusterTrackingService; try { connection = connFactoryService.getDefaultConnectionFactory().createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Topic dest = session.createTopic( ClusterTrackingService.EVENT_PING_CLUSTER_USER + "/" + EventUtils.safeTopicElement(serverId)); MessageConsumer consumer = session.createConsumer(dest); consumer.setMessageListener(this); connection.start(); } catch (JMSException e) { LOGGER.error(e.getMessage(), e); if (connection != null) { try { connection.close(); } catch (JMSException e1) { } } } }
public static void main(String[] args) throws JMSException { AsyncSimpleConsumer asyncConsumer = new AsyncSimpleConsumer(); ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url); Connection connection = connectionFactory.createConnection(); connection.start(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Destination destination = session.createQueue(subject); MessageConsumer consumer = session.createConsumer(destination); consumer.setMessageListener(asyncConsumer); connection.setExceptionListener(asyncConsumer); try { while (true) { if (AsyncSimpleConsumer.catchExit) { break; } Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println("Sleep interrupted"); } connection.close(); }
public void testSendManyMessages() throws Exception { MessageConsumer consumer = session.createConsumer(queue); String frame = "CONNECT\n" + "login: brianm\n" + "passcode: wombats\n\n" + Stomp.NULL; sendFrame(frame); frame = receiveFrame(10000); Assert.assertTrue(frame.startsWith("CONNECTED")); int count = 1000; final CountDownLatch latch = new CountDownLatch(count); consumer.setMessageListener( new MessageListener() { public void onMessage(Message arg0) { latch.countDown(); } }); frame = "SEND\n" + "destination:" + getQueuePrefix() + getQueueName() + "\n\n" + "Hello World" + Stomp.NULL; for (int i = 1; i <= count; i++) { // Thread.sleep(1); // System.out.println(">>> " + i); sendFrame(frame); } assertTrue(latch.await(60, TimeUnit.SECONDS)); }
public void testReceiveThenUseMessageListener() throws Exception { _logger.error("Test disabled as initial receive is not called first"); // Perform initial receive to start connection assertTrue(_consumer.receive(2000) != null); _receivedCount++; // Sleep to ensure remaining 4 msgs end up on _synchronousQueue Thread.sleep(1000); // Set the message listener and wait for the messages to come in. _consumer.setMessageListener(this); _logger.info("Waiting 3 seconds for messages"); try { _awaitMessages.await(3000, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { // do nothing } // Should have received all async messages assertEquals(MSG_COUNT, _receivedCount); _clientConnection.close(); Connection conn = getConnection("guest", "guest"); Session clientSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); Queue queue = clientSession.createQueue("message-listener-test-queue"); MessageConsumer cons = clientSession.createConsumer(queue); conn.start(); // check that the messages were actually dequeued assertTrue(cons.receive(2000) == null); }
/** * Listen to a message from JMS from a given destination by name. * * @param destinationName destinationName * @param messageListener messageListener */ public void listenTextMessagesWithDestination( final String destinationName, final Consumer<String> messageListener) { final MessageConsumer consumer = getConsumer(destinationName); try { consumer.setMessageListener( message -> { try { messageListener.accept(((TextMessage) message).getText()); if (acknowledgeMode == Session.CLIENT_ACKNOWLEDGE) { message.acknowledge(); } } catch (JMSException e) { throw new IllegalStateException( "Unable to register get text from message in listener " + destinationName, e); } catch (Exception ex) { throw new IllegalStateException("Unable handle JMS Consumer " + destinationName, ex); } }); } catch (JMSException e) { throw new IllegalStateException("Unable to register message listener " + destinationName, e); } }
private static String getResultFromQueue(String callId) throws JMSException, InterruptedException { Destination resultDest = session.createQueue(callId); MessageConsumer consumer = session.createConsumer(resultDest); final Semaphore messageSem = new Semaphore(0); final AtomicReference<String> resultReference = new AtomicReference<String>(); consumer.setMessageListener( new MessageListener() { @Override public void onMessage(Message message) { try { String text = ((TextMessage) message).getText(); resultReference.set(text); } catch (JMSException e) { throw new RuntimeException(e); } finally { messageSem.release(); } } }); LOGGER.info("waiting for response"); if (!messageSem.tryAcquire(10, TimeUnit.SECONDS)) { throw new RuntimeException("no response"); } LOGGER.info("response received"); return resultReference.get(); }
public static void consumeTopic() throws Exception { ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory( ActiveMQConnectionFactory.DEFAULT_USER, ActiveMQConnectionFactory.DEFAULT_PASSWORD, ActiveMQConnectionFactory.DEFAULT_BROKER_URL); Connection connection = connectionFactory.createConnection(); connection.setClientID(clientID); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Topic topic = session.createTopic(topicName); MessageConsumer consumer = session.createDurableSubscriber(topic, topicName); consumer.setMessageListener( new MessageListener() { public void onMessage(Message message) { TextMessage m = (TextMessage) message; try { System.out.println(m.getText()); } catch (JMSException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); connection.start(); }
public void start() throws JMSException { String selector = "next = '" + myId + "'"; try { ConnectionFactory factory = template.getConnectionFactory(); final Connection c = connection = factory.createConnection(); // we might be a reusable connection in spring // so lets only set the client ID once if its not set synchronized (c) { if (c.getClientID() == null) { c.setClientID(myId); } } connection.start(); session = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE); consumer = session.createConsumer(destination, selector, false); consumer.setMessageListener(this); } catch (JMSException ex) { LOG.error("", ex); throw ex; } }
public DigitalLibraryServer() { try { Properties properties = new Properties(); properties.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory"); properties.put(Context.URL_PKG_PREFIXES, "org.jnp.interfaces"); properties.put(Context.PROVIDER_URL, "localhost"); InitialContext jndi = new InitialContext(properties); ConnectionFactory conFactory = (ConnectionFactory) jndi.lookup("XAConnectionFactory"); connection = conFactory.createConnection(); session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); try { counterTopic = (Topic) jndi.lookup("counterTopic"); } catch (NamingException NE1) { System.out.println("NamingException: " + NE1 + " : Continuing anyway..."); } if (null == counterTopic) { counterTopic = session.createTopic("counterTopic"); jndi.bind("counterTopic", counterTopic); } consumer = session.createConsumer(counterTopic); consumer.setMessageListener(this); System.out.println("Server started waiting for client requests"); connection.start(); } catch (NamingException NE) { System.out.println("Naming Exception: " + NE); } catch (JMSException JMSE) { System.out.println("JMS Exception: " + JMSE); JMSE.printStackTrace(); } }
/** * Subsribes, collects, checking any set filters. A messageComsumer must be created before * calling this. If arg set to true, do a failsafe sub */ public void subscribe(boolean failsafe) throws JMSException { if (consumer == null) throw new JMSException("No messageConsumer created"); if (failsafe) connection.setExceptionListener(this); consumer.setMessageListener(this); }
public static void main(String[] args) throws Exception { Test advisory = new Test(); Session session = advisory.getSession(); for (String job : advisory.jobs) { ActiveMQDestination destination = (ActiveMQDestination) session.createQueue("JOBS." + job); Destination consumerTopic = AdvisorySupport.getConsumerAdvisoryTopic(destination); System.out.println("Subscribing to advisory " + consumerTopic); MessageConsumer consumerAdvisory = session.createConsumer(consumerTopic); consumerAdvisory.setMessageListener(new ConsumerAdvisoryListener()); Destination noConsumerTopic = AdvisorySupport.getNoQueueConsumersAdvisoryTopic(destination); System.out.println("Subscribing to advisory " + noConsumerTopic); MessageConsumer noConsumerAdvisory = session.createConsumer(noConsumerTopic); noConsumerAdvisory.setMessageListener(new NoConsumerAdvisoryListener()); } }
protected void doStop() throws UMOException { try { if (consumer != null) { consumer.setMessageListener(null); } } catch (JMSException e) { throw new LifecycleException(e, this); } }
private void subscribeForUpdates() throws JMSException { if (_ssn == null) { _ssn = _conn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageConsumer cons = _ssn.createConsumer( new AMQAnyDestination( "amq.failover", "amq.failover", "", true, true, null, false, new String[0])); cons.setMessageListener(this); } }
@Override public void start() { if (state.compareAndSet(State.INITIALIZED, State.STARTING)) { try { messageConsumer = jmsManager.createMessageConsumer(); messageConsumer.setMessageListener(this); } catch (final JMSException e) { throw new LoggingException(e); } } }
@Override public void start() { try { connection = connectionFactory.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); messageConsumer = session.createConsumer(schedulerQueue); messageConsumer.setMessageListener(this); connection.start(); } catch (JMSException e) { e.printStackTrace(); } }
public void testCannotUseMessageListener() throws Exception { Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageConsumer consumer = session.createConsumer(queue); MessageListener listener = new SpringConsumer(); try { consumer.setMessageListener(listener); fail("Should have thrown JMSException as we cannot use MessageListener with zero prefetch"); } catch (JMSException e) { LOG.info("Received expected exception : " + e); } }
public void _testSendCommitQueueCommitsInOrder() throws Exception { Connection conn = null; try { conn = createConnection(); Session producerSess = conn.createSession(true, Session.CLIENT_ACKNOWLEDGE); MessageProducer producer = producerSess.createProducer(queue1); producer.setDeliveryMode(DeliveryMode.PERSISTENT); Session consumerSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageConsumer consumer = consumerSession.createConsumer(queue1); CountDownLatch latch = new CountDownLatch(1); conn.start(); myReceiver myReceiver = new myReceiver(latch, conn); consumer.setMessageListener(myReceiver); long lastBatchTime = System.currentTimeMillis(); int sentId = 0; boolean started = false; // Send some messages while (true) { try { Message m = producerSess.createMessage(); m.setIntProperty("foo", sentId); sentId++; producer.send(m); if (sentId == 1 || System.currentTimeMillis() - lastBatchTime > 50) { lastBatchTime = System.currentTimeMillis(); producerSess.commit(); } } catch (JMSException e) { // ignore connection closed by consumer } // wait for the first message to be received before we continue sending if (!started) { Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); started = true; } else { if (myReceiver.failed) { throw myReceiver.e; } } } } finally { if (conn != null) { conn.close(); } removeAllMessages(queue1.getQueueName(), true); } }
/** * Create A Consumer for the given Topic and set the given {@link MessageListener}. * * @param topic The {@link Topic} to use * @param listener The {@link MessageListener} to set */ public synchronized void setupTopicListener(final String topic, final MessageListener listener) { this.checkAllowedState(State.SESSION_ACTIVE); final ActiveMQTopic top = new ActiveMQTopic(topic); MessageConsumer consumer; try { consumer = this.session.createConsumer(top); consumer.setMessageListener(listener); } catch (final JMSException ex) { LOGGER.error("Problems during setup of TopicListener.", ex); this.state = State.FAILURE; } }
public Receiver( final Session sess, final MessageConsumer cons, final int numMessages, final boolean isListener) throws Exception { super(sess, numMessages); this.cons = cons; this.isListener = isListener; if (this.isListener) { cons.setMessageListener(this); } }
/** * Create A Consumer for the given Queue and set the given {@link MessageListener}. * * @param destination The destination of the {@link Queue} * @param listener The {@link MessageListener} to set */ public synchronized void setupQueueListener( final String destination, final MessageListener listener) { this.checkAllowedState(State.SESSION_ACTIVE); final Destination dest = new ActiveMQQueue(destination); MessageConsumer consumer; try { consumer = this.session.createConsumer(dest); consumer.setMessageListener(listener); } catch (final JMSException ex) { LOGGER.error("Problems during setup of QueueListener.", ex); this.state = State.FAILURE; } }
public void testAsynchronousReceive() throws Exception { _consumer.setMessageListener(this); _logger.info("Waiting 3 seconds for messages"); try { _awaitMessages.await(3000, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { // do nothing } // Should have received all async messages assertEquals(MSG_COUNT, _receivedCount); }
@Override public MessageConsumerResources makeObject() throws Exception { MessageConsumerResources answer; Connection conn = getConnectionResource().borrowConnection(); try { Session session; if (isEndpointTransacted()) { session = conn.createSession(true, Session.SESSION_TRANSACTED); } else { session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); } Destination replyToDestination; if (ObjectHelper.isEmpty(getNamedReplyTo())) { replyToDestination = getEndpoint() .getDestinationCreationStrategy() .createTemporaryDestination(session, isTopic()); } else { replyToDestination = getEndpoint() .getDestinationCreationStrategy() .createDestination(session, getNamedReplyTo(), isTopic()); } MessageConsumer messageConsumer = JmsObjectFactory.createMessageConsumer( session, replyToDestination, null, isTopic(), null, true); messageConsumer.setMessageListener( new MessageListener() { @Override public void onMessage(final Message message) { log.debug("Message Received in the Consumer Pool"); log.debug(" Message : {}", message); try { Exchanger<Object> exchanger = EXCHANGERS.get(message.getJMSCorrelationID()); exchanger.exchange(message, getResponseTimeOut(), TimeUnit.MILLISECONDS); } catch (Exception e) { log.error("Unable to exchange message: {}", message, e); } } }); answer = new MessageConsumerResources(session, messageConsumer, replyToDestination); } catch (Exception e) { log.error("Unable to create the MessageConsumerResource: " + e.getLocalizedMessage()); throw new CamelException(e); } finally { getConnectionResource().returnConnection(conn); } return answer; }
/** * Starts a connection which listens to the topic and if a cancel is found published, tries to * terminate the subprocess. * * @param p */ protected void createTerminateListener() throws Exception { ConnectionFactory connectionFactory = ConnectionFactoryFacade.createConnectionFactory(uri); ProgressableProcess.this.topicConnection = connectionFactory.createConnection(); topicConnection.start(); Session session = topicConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); final Topic topic = session.createTopic(statusTName); final MessageConsumer consumer = session.createConsumer(topic); final Class<? extends StatusBean> clazz = bean.getClass(); final ObjectMapper mapper = new ObjectMapper(); MessageListener listener = new MessageListener() { public void onMessage(Message message) { try { if (message instanceof TextMessage) { TextMessage t = (TextMessage) message; final StatusBean tbean = mapper.readValue(t.getText(), clazz); if (bean.getStatus().isFinal()) { // Something else already happened topicConnection.close(); return; } if (bean.getUniqueId().equals(tbean.getUniqueId())) { if (tbean.getStatus() == Status.REQUEST_TERMINATE) { bean.merge(tbean); out.println("Terminating job '" + tbean.getName() + "'"); terminate(); topicConnection.close(); bean.setStatus(Status.TERMINATED); bean.setMessage("Foricibly terminated before finishing."); broadcast(bean); return; } } } } catch (Exception e) { logger.error("Cannot deal with message " + message, e); } } }; consumer.setMessageListener(listener); }