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; } }
@Override @Test(timeout = 30000) public void testMessageSizeOneDurable() throws Exception { AtomicLong publishedMessageSize = new AtomicLong(); Connection connection = new ActiveMQConnectionFactory(brokerConnectURI).createConnection(); connection.setClientID("clientId"); connection.start(); SubscriptionKey subKey = new SubscriptionKey("clientId", "sub1"); org.apache.activemq.broker.region.Topic dest = publishTestMessagesDurable( connection, new String[] {"sub1"}, 200, publishedMessageSize, DeliveryMode.PERSISTENT); verifyPendingStats(dest, subKey, 200, publishedMessageSize.get()); // The expected value is only 100 because for durables a LRUCache is being used // with a max size of 100 verifyStoreStats(dest, 100, publishedMessageSize.get()); // consume 100 messages consumeDurableTestMessages(connection, "sub1", 100, publishedMessageSize); // 100 should be left verifyPendingStats(dest, subKey, 100, publishedMessageSize.get()); verifyStoreStats(dest, 100, publishedMessageSize.get()); connection.close(); }
@Override @Test(timeout = 30000) public void testMessageSizeTwoDurables() throws Exception { AtomicLong publishedMessageSize = new AtomicLong(); Connection connection = new ActiveMQConnectionFactory(brokerConnectURI).createConnection(); connection.setClientID("clientId"); connection.start(); org.apache.activemq.broker.region.Topic dest = publishTestMessagesDurable( connection, new String[] {"sub1", "sub2"}, 200, publishedMessageSize, DeliveryMode.PERSISTENT); // verify the count and size SubscriptionKey subKey = new SubscriptionKey("clientId", "sub1"); verifyPendingStats(dest, subKey, 200, publishedMessageSize.get()); // consume messages just for sub1 consumeDurableTestMessages(connection, "sub1", 200, publishedMessageSize); // There is still a durable that hasn't consumed so the messages should exist SubscriptionKey subKey2 = new SubscriptionKey("clientId", "sub2"); verifyPendingStats(dest, subKey, 0, 0); verifyPendingStats(dest, subKey2, 200, publishedMessageSize.get()); // The expected value is only 100 because for durables a LRUCache is being used // with a max size of 100 verifyStoreStats(dest, 100, publishedMessageSize.get()); connection.stop(); }
public void testWithConnectionFactoryAndClientId() throws JMSException { MockControl cfControl = MockControl.createControl(ConnectionFactory.class); ConnectionFactory cf = (ConnectionFactory) cfControl.getMock(); MockControl conControl = MockControl.createControl(Connection.class); Connection con = (Connection) conControl.getMock(); cf.createConnection(); cfControl.setReturnValue(con, 1); con.setClientID("myId"); conControl.setVoidCallable(1); con.start(); conControl.setVoidCallable(1); con.stop(); conControl.setVoidCallable(1); con.close(); conControl.setVoidCallable(1); cfControl.replay(); conControl.replay(); SingleConnectionFactory scf = new SingleConnectionFactory(cf); scf.setClientId("myId"); Connection con1 = scf.createConnection(); con1.start(); con1.close(); // should be ignored Connection con2 = scf.createConnection(); con2.start(); con2.close(); // should be ignored scf.destroy(); // should trigger actual close cfControl.verify(); conControl.verify(); }
@Override @Test(timeout = 30000) public void testMessageSizeOneDurablePartialConsumption() throws Exception { AtomicLong publishedMessageSize = new AtomicLong(); Connection connection = new ActiveMQConnectionFactory(brokerConnectURI).createConnection(); connection.setClientID("clientId"); connection.start(); SubscriptionKey subKey = new SubscriptionKey("clientId", "sub1"); org.apache.activemq.broker.region.Topic dest = publishTestMessagesDurable( connection, new String[] {"sub1"}, 200, publishedMessageSize, DeliveryMode.PERSISTENT); // verify the count and size - durable is offline so all 200 should be pending since none are in // prefetch verifyPendingStats(dest, subKey, 200, publishedMessageSize.get()); // The expected value is only 100 because for durables a LRUCache is being used // with a max size of 100 verifyStoreStats(dest, 100, publishedMessageSize.get()); // consume all messages consumeDurableTestMessages(connection, "sub1", 50, publishedMessageSize); // All messages should now be gone verifyPendingStats(dest, subKey, 150, publishedMessageSize.get()); // The expected value is only 100 because for durables a LRUCache is being used // with a max size of 100 // verify the size is at least as big as 100 messages times the minimum of 100 size verifyStoreStats(dest, 100, 100 * 100); connection.close(); }
/** * Title: getMQSession Description:取得session Created On: 2015-4-1 下午7:07:07 * * @author jason * @return */ protected Session getMQSession() { if (mqSession != null) { return mqSession; } try { // 创建MQ连接 ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerUrl); mqConnection = connectionFactory.createConnection(); if (log != null) { log.debug("mqConnection to MQ '" + brokerUrl + "'"); log.debug("MQ clientId is:" + clientId); } // 设置ClientID mqConnection.setClientID(clientId); // 创建Session mqSession = mqConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); // 启动连接 mqConnection.start(); return mqSession; } catch (JMSException e) { if (log != null) { log.error("Connect to MQ '" + brokerUrl + "' failed!", e); } } return null; }
/** * Check a session is rollbacked on a Session close(); * * @throws Exception */ public void xtestTransactionRollbackOnSessionClose() throws Exception { Destination destination = createDestination(getClass().getName()); Connection connection = createConnection(); connection.setClientID(idGen.generateId()); connection.start(); Session consumerSession = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE); MessageConsumer consumer = null; if (topic) { consumer = consumerSession.createDurableSubscriber((Topic) destination, "TESTRED"); } else { consumer = consumerSession.createConsumer(destination); } Session producerSession = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = producerSession.createProducer(destination); producer.setDeliveryMode(deliveryMode); TextMessage sentMsg = producerSession.createTextMessage(); sentMsg.setText("msg1"); producer.send(sentMsg); producerSession.commit(); Message recMsg = consumer.receive(RECEIVE_TIMEOUT); assertFalse(recMsg.getJMSRedelivered()); consumerSession.close(); consumerSession = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE); consumer = consumerSession.createConsumer(destination); recMsg = consumer.receive(RECEIVE_TIMEOUT); consumerSession.commit(); assertTrue(recMsg.equals(sentMsg)); connection.close(); }
public static void main(String[] argv) throws Exception { clientId = "Listener-" + System.currentTimeMillis(); NDC.push(clientId); Config config = new Config(); config.setOptions(argv); // Connection con = config.createConnection(); Connection con = new AMQConnection( "amqp://*****:*****@testid/test?brokerlist='" + config.getHost() + ":" + config.getPort() + "'"); if (config.getClientId() != null) { con.setClientID(config.getClientId()); } new Listener(con, config.getAckMode(), config.getSubscriptionId()); NDC.pop(); NDC.remove(); }
/** * Prepare the given Connection before it is exposed. * <p>The default implementation applies ExceptionListener and client id. * Can be overridden in subclasses. * @param con the Connection to prepare * @throws JMSException if thrown by JMS API methods * @see #setExceptionListener * @see #setReconnectOnException */ protected void prepareConnection(Connection con) throws JMSException { if (getClientId() != null) { con.setClientID(getClientId()); } if (getExceptionListener() != null || isReconnectOnException()) { ExceptionListener listenerToUse = getExceptionListener(); if (isReconnectOnException()) { listenerToUse = new InternalChainedExceptionListener(this, listenerToUse); } con.setExceptionListener(listenerToUse); } }
@Override public Connection getJmsConnection(String connectionId) { // jmsConnectionFactory.setClientId("abcPlatform_webclient_" +); Connection conn = null; try { conn = jmsConnectionFactory.createConnection(); conn.setClientID(String.valueOf(System.currentTimeMillis())); conn.start(); } catch (JMSException e) { e.printStackTrace(); } return conn; }
/** * Constructor takes the necessary JNDI related parameters to create a connection and create an * onMessageListener to prepare to begin receiving messages. <br> * The caller must then invoke {@link #start()} to enable message reception. * * @param queueSize maximum queue size <=0 == no limit * @param useProps if true, use jndi.properties instead of initialContextFactory, providerUrl, * securityPrincipal, securityCredentials * @param initialContextFactory * @param providerUrl * @param connfactory * @param destinationName * @param durableSubscriptionId * @param clientId * @param jmsSelector Message Selector * @param useAuth * @param securityPrincipal * @param securityCredentials * @param useMessageListener if true create an onMessageListener to prepare to begin receiving * messages, otherwise queue will be null * @throws JMSException if could not create context or other problem occurred. * @throws NamingException */ private ReceiveSubscriber( int queueSize, boolean useProps, String initialContextFactory, String providerUrl, String connfactory, String destinationName, String durableSubscriptionId, String clientId, String jmsSelector, boolean useAuth, String securityPrincipal, String securityCredentials, boolean useMessageListener) throws NamingException, JMSException { boolean initSuccess = false; try { Context ctx = InitialContextFactory.getContext( useProps, initialContextFactory, providerUrl, useAuth, securityPrincipal, securityCredentials); CONN = Utils.getConnection(ctx, connfactory); if (!isEmpty(clientId)) { CONN.setClientID(clientId); } SESSION = CONN.createSession(false, Session.AUTO_ACKNOWLEDGE); Destination dest = Utils.lookupDestination(ctx, destinationName); SUBSCRIBER = createSubscriber(SESSION, dest, durableSubscriptionId, jmsSelector); if (useMessageListener) { if (queueSize <= 0) { queue = new LinkedBlockingQueue<Message>(); } else { queue = new LinkedBlockingQueue<Message>(queueSize); } SUBSCRIBER.setMessageListener(this); } else { queue = null; } log.debug("<init> complete"); initSuccess = true; } finally { if (!initSuccess) { close(); } } }
/** * test messages are acknowledged and recovered properly * * @throws Exception */ public void testClientAcknowledge() throws Exception { Destination destination = createDestination(getClass().getName()); Connection connection = createConnection(); connection.setClientID(idGen.generateId()); connection.start(); Session consumerSession = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); MessageConsumer consumer = consumerSession.createConsumer(destination); Session producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = producerSession.createProducer(destination); producer.setDeliveryMode(deliveryMode); // send some messages TextMessage sent1 = producerSession.createTextMessage(); sent1.setText("msg1"); sent1.setStringProperty("str", "1"); producer.send(sent1); TextMessage sent2 = producerSession.createTextMessage(); sent2.setText("msg2"); sent2.setStringProperty("str", "2"); producer.send(sent2); TextMessage sent3 = producerSession.createTextMessage(); sent2.setText("msg3"); sent2.setStringProperty("str", "3"); producer.send(sent3); TextMessage msgTest = (TextMessage) consumer.receive(RECEIVE_TIMEOUT); System.out.println("msgTest::" + msgTest + " // " + msgTest.getText()); TextMessage rec2 = (TextMessage) consumer.receive(RECEIVE_TIMEOUT); System.out.println("msgTest::" + rec2 + " // " + rec2.getText()); assertNull(consumer.receiveNoWait()); // ack rec2 rec2.acknowledge(); TextMessage sent4 = producerSession.createTextMessage(); sent4.setText("msg4"); producer.send(sent4); TextMessage rec4 = (TextMessage) consumer.receive(RECEIVE_TIMEOUT); assertTrue(rec4.equals(sent4)); consumerSession.recover(); rec4 = (TextMessage) consumer.receive(RECEIVE_TIMEOUT); assertTrue(rec4.equals(sent4)); assertTrue(rec4.getJMSRedelivered()); rec4.acknowledge(); connection.close(); }
private Connection createConnection( final String username, final String password, final ConnectionFactoryFactory cff, final String clientID, final boolean isXA) throws Exception { Connection conn; Object cf = cff.createConnectionFactory(); if (qualityOfServiceMode == QualityOfServiceMode.ONCE_AND_ONLY_ONCE && !(cf instanceof XAConnectionFactory)) { throw new IllegalArgumentException("Connection factory must be XAConnectionFactory"); } if (username == null) { if (isXA) { if (JMSBridgeImpl.trace) { HornetQJMSServerLogger.LOGGER.trace("Creating an XA connection"); } conn = ((XAConnectionFactory) cf).createXAConnection(); } else { if (JMSBridgeImpl.trace) { HornetQJMSServerLogger.LOGGER.trace("Creating a non XA connection"); } conn = ((ConnectionFactory) cf).createConnection(); } } else { if (isXA) { if (JMSBridgeImpl.trace) { HornetQJMSServerLogger.LOGGER.trace("Creating an XA connection"); } conn = ((XAConnectionFactory) cf).createXAConnection(username, password); } else { if (JMSBridgeImpl.trace) { HornetQJMSServerLogger.LOGGER.trace("Creating a non XA connection"); } conn = ((ConnectionFactory) cf).createConnection(username, password); } } if (clientID != null) { conn.setClientID(clientID); } conn.setExceptionListener(new BridgeExceptionListener()); return conn; }
private ActiveMQTopic registerDurableConsumer( BrokerService brokerService, MessageListener listener) throws Exception { ConnectionFactory factory = createConnectionFactory(brokerService); Connection connection = factory.createConnection(); connection.setClientID("DurableOne"); connection.start(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); ActiveMQTopic destination = (ActiveMQTopic) session.createTopic(DESTINATION_NAME); // unique to a broker TopicSubscriber sub = session.createDurableSubscriber(destination, "SubOne" + brokerService.getBrokerName()); sub.setMessageListener(listener); return destination; }
public static void main(String[] args) { ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("admin", "password", BROKER_URL); Connection connection = null; try { connection = connectionFactory.createConnection(); connection.setClientID("duravel"); connection.start(); Session session = connection.createSession(NON_TRANSACTED, Session.AUTO_ACKNOWLEDGE); Destination destination; MessageProducer producer = null; for (int i = 0; i < NUM_MESSAGES_TO_SEND; i++) { System.out.println("Sending message #" + i); Operacao op = gerarOperacao(); destination = session.createTopic(op.getDescricao()); producer = session.createProducer(destination); ObjectMessage message = session.createObjectMessage(op); swingBasic.start(op); producer.send(message); Thread.sleep(DELAY); } producer.send(session.createTextMessage("END")); producer.close(); session.close(); } catch (Exception e) { e.printStackTrace(); } finally { if (connection != null) { try { connection.close(); } catch (JMSException e) { e.printStackTrace(); } } } }
public void testNoExceptionOnRedeliveryAckWithSimpleTopicConsumer() throws Exception { Destination destination = createDestination(getClass().getName()); Connection connection = createConnection(); final AtomicBoolean gotException = new AtomicBoolean(); connection.setExceptionListener( new ExceptionListener() { @Override public void onException(JMSException exception) { LOG.error("unexpected ex:" + exception); gotException.set(true); } }); connection.setClientID(idGen.generateId()); connection.start(); Session consumerSession = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE); MessageConsumer consumer = null; if (topic) { consumer = consumerSession.createConsumer(destination); } else { consumer = consumerSession.createConsumer(destination); } Session producerSession = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = producerSession.createProducer(destination); producer.setDeliveryMode(deliveryMode); TextMessage sentMsg = producerSession.createTextMessage(); sentMsg.setText("msg1"); producer.send(sentMsg); producerSession.commit(); Message recMsg = consumer.receive(RECEIVE_TIMEOUT); assertFalse(recMsg.getJMSRedelivered()); recMsg = consumer.receive(RECEIVE_TIMEOUT); consumerSession.rollback(); recMsg = consumer.receive(RECEIVE_TIMEOUT); assertTrue(recMsg.getJMSRedelivered()); consumerSession.rollback(); recMsg = consumer.receive(RECEIVE_TIMEOUT); assertTrue(recMsg.getJMSRedelivered()); consumerSession.commit(); assertTrue(recMsg.equals(sentMsg)); assertTrue(recMsg.getJMSRedelivered()); connection.close(); assertFalse("no exception", gotException.get()); }
/** * Connection specific setup for JMS. * * @throws JMSException */ public void createConnection() throws JMSException { connection = getConnectionFactory().createConnection(); if (durable && clientId != null) { connection.setClientID(clientId); } logger.debug("Before starting connection."); connection.start(); logger.debug("After starting connection."); // Create session session = connection.createSession(transacted, getSessionAckMode(ackMode)); // Create destination destination = topic ? session.createTopic(subject) : session.createQueue(subject); }
public void testDurableSubscriber() throws Exception { BridgeImpl bridge = null; try { final int NUM_MESSAGES = 10; bridge = new BridgeImpl( cff0, cff1, sourceTopicFactory, targetQueueFactory, null, null, null, null, null, 5000, 10, QualityOfServiceMode.AT_MOST_ONCE, 1, -1, "subTest", "clientid123", false); bridge.start(); sendMessages(cf0, sourceTopic, 0, NUM_MESSAGES, true); checkAllMessageReceivedInOrder(cf1, targetQueue, 0, NUM_MESSAGES); } finally { if (bridge != null) { bridge.stop(); } // Now unsubscribe Connection conn = cf0.createConnection(); conn.setClientID("clientid123"); Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); sess.unsubscribe("subTest"); conn.close(); } }
public void run() { try { ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(user, password, url); Connection connection = connectionFactory.createConnection(); if (clientId != null && clientId.length() > 0 && !"null".equals(clientId)) { connection.setClientID(clientId); } connection.setExceptionListener(this); connection.start(); session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); destination = session.createTopic(subject); MessageConsumer consumer = session.createDurableSubscriber((Topic) destination, consumerName); consumer.setMessageListener(this); } catch (Exception e) { System.out.println("Caught: " + e); e.printStackTrace(); } }
/** * check messages are actuallly sent on a tx rollback * * @throws Exception */ public void testTransactionRollbackOnSend() throws Exception { Destination destination = createDestination(getClass().getName()); Connection connection = createConnection(); connection.setClientID(idGen.generateId()); connection.start(); Session consumerSession = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE); MessageConsumer consumer = consumerSession.createConsumer(destination); Session producerSession = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = producerSession.createProducer(destination); producer.setDeliveryMode(deliveryMode); TextMessage sentMsg = producerSession.createTextMessage(); sentMsg.setText("msg1"); producer.send(sentMsg); producerSession.commit(); Message recMsg = consumer.receive(RECEIVE_TIMEOUT); consumerSession.commit(); assertTrue(recMsg.equals(sentMsg)); sentMsg = producerSession.createTextMessage(); sentMsg.setText("msg2"); producer.send(sentMsg); producerSession.rollback(); sentMsg = producerSession.createTextMessage(); sentMsg.setText("msg3"); producer.send(sentMsg); producerSession.commit(); recMsg = consumer.receive(RECEIVE_TIMEOUT); assertTrue(recMsg.equals(sentMsg)); consumerSession.commit(); connection.close(); }
protected void useConnection(Connection connection) throws JMSException { connection.setClientID("foo"); connection.start(); }
@Test public void testPagingOverCreatedDestinationQueues() throws Exception { Configuration config = createDefaultConfig(); config.setJournalSyncNonTransactional(false); HornetQServer server = createServer( true, config, -1, -1, AddressFullMessagePolicy.BLOCK, new HashMap<String, AddressSettings>()); JMSServerManagerImpl jmsServer = new JMSServerManagerImpl(server); InVMNamingContext context = new InVMNamingContext(); jmsServer.setContext(context); jmsServer.start(); server .getHornetQServerControl() .addAddressSettings( "jms.queue.Q1", "DLQ", "DLQ", -1, false, 5, 100 * 1024, 10 * 1024, 5, 5, 1, 1000, 0, false, "PAGE", -1, 10, "KILL"); jmsServer.createQueue(true, "Q1", null, true, "/queue/Q1"); HornetQJMSConnectionFactory cf = (HornetQJMSConnectionFactory) HornetQJMSClient.createConnectionFactoryWithoutHA( JMSFactoryType.CF, new TransportConfiguration(INVM_CONNECTOR_FACTORY)); conn = cf.createConnection(); conn.setClientID("tst"); Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); javax.jms.Queue queue = (javax.jms.Queue) context.lookup("/queue/Q1"); MessageProducer prod = sess.createProducer(queue); prod.setDeliveryMode(DeliveryMode.PERSISTENT); BytesMessage bmt = sess.createBytesMessage(); bmt.writeBytes(new byte[1024]); for (int i = 0; i < 500; i++) { prod.send(bmt); } PagingStore store = server.getPagingManager().getPageStore(new SimpleString("jms.queue.Q1")); assertEquals(100 * 1024, store.getMaxSize()); assertEquals(10 * 1024, store.getPageSizeBytes()); assertEquals(AddressFullMessagePolicy.PAGE, store.getAddressFullMessagePolicy()); jmsServer.stop(); server = createServer( true, config, -1, -1, AddressFullMessagePolicy.BLOCK, new HashMap<String, AddressSettings>()); jmsServer = new JMSServerManagerImpl(server); context = new InVMNamingContext(); jmsServer.setContext(context); jmsServer.start(); AddressSettings settings = server.getAddressSettingsRepository().getMatch("jms.queue.Q1"); assertEquals(100 * 1024, settings.getMaxSizeBytes()); assertEquals(10 * 1024, settings.getPageSizeBytes()); assertEquals(AddressFullMessagePolicy.PAGE, settings.getAddressFullMessagePolicy()); store = server.getPagingManager().getPageStore(new SimpleString("jms.queue.Q1")); assertEquals(100 * 1024, store.getMaxSize()); assertEquals(10 * 1024, store.getPageSizeBytes()); assertEquals(AddressFullMessagePolicy.PAGE, store.getAddressFullMessagePolicy()); }
@Override public int run() throws Exception { // Default values of command line arguments String host = DEFAULT_HOST; int port = DEFAULT_PORT; String user = DEFAULT_USER; String pass = DEFAULT_PASS; String destination = DEFAULT_DESTINATION; String file = ""; // No default -- if not given, don't read/write file int sleep = 0; boolean showpercent = false; int batchSize = 0; int length = 500; // Length of message generated internally String properties = ""; String format = "short"; String durable = null; int n = 1; // n is the number of messages to process, or a specific // message number, depending on content String url = ""; // No default -- if not given, don't use it String[] nonSwitchArgs = cl.getArgs(); if (nonSwitchArgs.length > 0) n = Integer.parseInt(nonSwitchArgs[0]); String _destination = cl.getOptionValue("destination"); if (_destination != null) destination = _destination; String _host = cl.getOptionValue("host"); if (_host != null) host = _host; String _port = cl.getOptionValue("port"); if (_port != null) port = Integer.parseInt(_port); String _file = cl.getOptionValue("file"); if (_file != null) file = _file; String _user = cl.getOptionValue("user"); if (_user != null) user = _user; String _pass = cl.getOptionValue("password"); if (_pass != null) pass = _pass; String _url = cl.getOptionValue("url"); if (_url != null) url = _url; String _sleep = cl.getOptionValue("sleep"); if (_sleep != null) sleep = Integer.parseInt(_sleep); if (cl.hasOption("percent")) showpercent = true; String _batchSize = cl.getOptionValue("batch"); if (_batchSize != null) batchSize = Integer.parseInt(_batchSize); String _L = cl.getOptionValue("length"); if (_L != null) length = Integer.parseInt(_L); String _properties = cl.getOptionValue("properties"); if (_properties != null) properties = _properties; String _durable = cl.getOptionValue("durable"); if (_durable != null) durable = _durable; boolean batch = false; if (batchSize != 0) batch = true; String _format = cl.getOptionValue("format"); if (_format != null) format = _format; ActiveMQConnectionFactory factory = getFactory(host, port, url); Connection connection = factory.createConnection(user, pass); if (durable != null) connection.setClientID(durable); connection.start(); Session session = connection.createSession(batch, Session.AUTO_ACKNOWLEDGE); Topic topic = session.createTopic(destination); MessageConsumer consumer = null; if (durable != null) consumer = session.createDurableSubscriber(topic, "amqutil"); else consumer = session.createConsumer(topic); int oldpercent = 0; for (int i = 0; i < n; i++) { javax.jms.Message message = consumer.receive(); if (batch) if ((i + 1) % batchSize == 0) session.commit(); if (sleep != 0) Thread.sleep(sleep); JMSUtil.outputMessage(format, message, file); if (showpercent) { int percent = i * 100 / n; if (percent != oldpercent) System.out.println("" + percent + "%"); oldpercent = percent; } } if (batch) session.commit(); connection.close(); return 0; }
@Test public void testSendTopic() throws Exception { Topic topic = createTopic("topic"); Connection conn = cf.createConnection(); try { conn.setClientID("someID"); Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageConsumer cons = sess.createDurableSubscriber(topic, "someSub"); conn.start(); MessageProducer prod = sess.createProducer(topic); TextMessage msg1 = sess.createTextMessage("text"); prod.send(msg1); assertNotNull(cons.receive(5000)); conn.close(); StorageManager storage = server.getStorageManager(); for (int i = 0; i < 100; i++) { long txid = storage.generateUniqueID(); final Queue queue = new QueueImpl( storage.generateUniqueID(), SimpleString.toSimpleString("jms.topic.topic"), SimpleString.toSimpleString("jms.topic.topic"), FilterImpl.createFilter(HornetQServerImpl.GENERIC_IGNORED_FILTER), true, false, server.getScheduledPool(), server.getPostOffice(), storage, server.getAddressSettingsRepository(), server.getExecutorFactory().getExecutor()); LocalQueueBinding binding = new LocalQueueBinding(queue.getAddress(), queue, server.getNodeID()); storage.addQueueBinding(txid, binding); storage.commitBindings(txid); } jmsServer.stop(); jmsServer.start(); } finally { try { conn.close(); } catch (Throwable igonred) { } } }
public void testExpireMessagesForDurableSubscriber() throws Exception { createBroker(); ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connectionUri); connection = factory.createConnection(); connection.setClientID("myConnection"); session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); connection.start(); Topic destination = session.createTopic("test"); producer = session.createProducer(destination); final int ttl = 1000; producer.setTimeToLive(ttl); final long sendCount = 10; TopicSubscriber sub = session.createDurableSubscriber(destination, "mySub"); sub.close(); for (int i = 0; i < sendCount; i++) { producer.send(session.createTextMessage("test")); } DestinationViewMBean view = createView((ActiveMQTopic) destination); LOG.info("messages sent"); LOG.info("expired=" + view.getExpiredCount() + " " + view.getEnqueueCount()); assertEquals(0, view.getExpiredCount()); assertEquals(10, view.getEnqueueCount()); Thread.sleep(5000); LOG.info("expired=" + view.getExpiredCount() + " " + view.getEnqueueCount()); assertEquals(10, view.getExpiredCount()); assertEquals(10, view.getEnqueueCount()); final AtomicLong received = new AtomicLong(); sub = session.createDurableSubscriber(destination, "mySub"); sub.setMessageListener( new MessageListener() { @Override public void onMessage(Message message) { received.incrementAndGet(); } }); LOG.info("Waiting for messages to arrive"); Wait.waitFor( new Wait.Condition() { @Override public boolean isSatisified() throws Exception { return received.get() >= sendCount; } }, 1000); LOG.info("received=" + received.get()); LOG.info("expired=" + view.getExpiredCount() + " " + view.getEnqueueCount()); assertEquals(0, received.get()); assertEquals(10, view.getExpiredCount()); assertEquals(10, view.getEnqueueCount()); }
@Test public void testSendToSingleDisconnectedBinding() throws Exception { Connection conn1 = cf1.createConnection(); conn1.setClientID("someClient1"); Connection conn2 = cf2.createConnection(); conn2.setClientID("someClient2"); conn1.start(); conn2.start(); try { Topic topic1 = createTopic("t1", true); Topic topic2 = (Topic) context1.lookup("topic/t1"); Session session1 = conn1.createSession(false, Session.AUTO_ACKNOWLEDGE); Session session2 = conn2.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageConsumer cons2 = session2.createDurableSubscriber(topic2, "sub2"); cons2.close(); session2.close(); conn2.close(); Thread.sleep(500); MessageProducer prod1 = session1.createProducer(topic1); prod1.setDeliveryMode(DeliveryMode.PERSISTENT); prod1.send(session1.createTextMessage("m1")); printBindings(jmsServer1.getActiveMQServer(), "jms.topic.t1"); printBindings(jmsServer2.getActiveMQServer(), "jms.topic.t1"); crash(); printBindings(jmsServer1.getActiveMQServer(), "jms.topic.t1"); prod1.send(session1.createTextMessage("m2")); restart(); Thread.sleep(2000); printBindings(jmsServer1.getActiveMQServer(), "jms.topic.t1"); printBindings(jmsServer2.getActiveMQServer(), "jms.topic.t1"); prod1.send(session1.createTextMessage("m3")); cf2 = ActiveMQJMSClient.createConnectionFactoryWithoutHA( JMSFactoryType.CF, new TransportConfiguration( InVMConnectorFactory.class.getName(), generateInVMParams(2))); conn2 = cf2.createConnection(); conn2.setClientID("someClient2"); session2 = conn2.createSession(false, Session.AUTO_ACKNOWLEDGE); cons2 = session2.createDurableSubscriber(topic2, "sub2"); conn2.start(); TextMessage received = (TextMessage) cons2.receive(5000); assertNotNull(received); assertEquals("m1", received.getText()); received = (TextMessage) cons2.receive(5000); assertNotNull(received); assertEquals("m2", received.getText()); received = (TextMessage) cons2.receive(5000); assertNotNull(received); assertEquals("m3", received.getText()); cons2.close(); } finally { conn1.close(); conn2.close(); } jmsServer1.destroyTopic("t1"); jmsServer2.destroyTopic("t1"); }
@Test public void testPagingOverCreatedDestinationTopics() throws Exception { Configuration config = createDefaultConfig(); config.setJournalSyncNonTransactional(false); HornetQServer server = createServer(true, config, PAGE_SIZE, -1, new HashMap<String, AddressSettings>()); JMSServerManagerImpl jmsServer = new JMSServerManagerImpl(server); InVMNamingContext context = new InVMNamingContext(); jmsServer.setContext(context); jmsServer.start(); jmsServer.createTopic(true, "tt", "/topic/TT"); server .getHornetQServerControl() .addAddressSettings( "jms.topic.TT", "DLQ", "DLQ", -1, false, 5, 1024 * 1024, 1024 * 10, 5, 5, 1, 1000, 0, false, "PAGE", -1, 10, "KILL"); HornetQJMSConnectionFactory cf = (HornetQJMSConnectionFactory) HornetQJMSClient.createConnectionFactoryWithoutHA( JMSFactoryType.CF, new TransportConfiguration(INVM_CONNECTOR_FACTORY)); Connection conn = cf.createConnection(); conn.setClientID("tst"); Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); Topic topic = (Topic) context.lookup("/topic/TT"); sess.createDurableSubscriber(topic, "t1"); MessageProducer prod = sess.createProducer(topic); prod.setDeliveryMode(DeliveryMode.PERSISTENT); TextMessage txt = sess.createTextMessage("TST"); prod.send(txt); PagingStore store = server.getPagingManager().getPageStore(new SimpleString("jms.topic.TT")); assertEquals(1024 * 1024, store.getMaxSize()); assertEquals(10 * 1024, store.getPageSizeBytes()); jmsServer.stop(); server = createServer(true, config, PAGE_SIZE, -1, new HashMap<String, AddressSettings>()); jmsServer = new JMSServerManagerImpl(server); context = new InVMNamingContext(); jmsServer.setContext(context); jmsServer.start(); AddressSettings settings = server.getAddressSettingsRepository().getMatch("jms.topic.TT"); assertEquals(1024 * 1024, settings.getMaxSizeBytes()); assertEquals(10 * 1024, settings.getPageSizeBytes()); assertEquals(AddressFullMessagePolicy.PAGE, settings.getAddressFullMessagePolicy()); store = server.getPagingManager().getPageStore(new SimpleString("TT")); conn.close(); server.stop(); }
public void run() { Connection connection = null; try { ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(connProps.getString("url")); connection = connectionFactory.createConnection( connProps.getString("user"), connProps.getString("password")); connection.setClientID("demoClient"); connection.start(); connection.setExceptionListener(this); Session session = connection.createSession( Boolean.parseBoolean(connProps.getString("transacted")), Session.AUTO_ACKNOWLEDGE); // non durable subscriber // Destination destination = session.createTopic(topicName); // MessageConsumer consumer = session.createConsumer(destination); // durable subscriber // Topic topic = session.createTopic(topicName); // MessageConsumer consumer = session.createDurableSubscriber(topic, "demoConsumer"); Queue queue = session.createQueue(connProps.getString("queueName")); MessageConsumer consumer = session.createConsumer(queue); System.out.println("Starting consumer..."); for (int i = 1; i <= max_iter; i++) { Message message = consumer.receive(2000); System.out.println("Iteration (" + i + "/" + max_iter + ")"); if (message instanceof TextMessage) { TextMessage textMessage = (TextMessage) message; String text = textMessage.getText(); System.out.println(i + ". Received: " + text); } else if (message instanceof ActiveMQBytesMessage) { ActiveMQBytesMessage bytesMessage = (ActiveMQBytesMessage) message; ByteSequence bytesSeq = bytesMessage.getContent(); String text = new String(bytesSeq.data); System.out.println(i + ". Decoded: " + text); } else if (message == null) { System.out.println(i + ". No messages received"); } else { System.out.println(i + ". Received: " + message); } } System.out.println("Closing consumer."); consumer.close(); session.close(); } catch (Exception e) { System.out.println("Caught: " + e); e.printStackTrace(); } finally { if (connection != null) { try { connection.close(); } catch (Exception e) { System.out.println("Caught: " + e); e.printStackTrace(); } } } }
@Test public void testRemoteBindingRemovedOnReconnectLocalAvailable() throws Exception { Connection conn1 = cf1.createConnection(); conn1.setClientID("someClient2"); Connection conn2 = cf2.createConnection(); conn2.setClientID("someClient2"); conn1.start(); conn2.start(); try { Topic topic1 = createTopic("t1", true); Topic topic2 = (Topic) context1.lookup("topic/t1"); Session session1 = conn1.createSession(false, Session.AUTO_ACKNOWLEDGE); Session session2 = conn2.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageConsumer cons1 = session1.createSharedConsumer(topic1, "sub2"); MessageConsumer cons2 = session2.createSharedConsumer(topic2, "sub2"); Thread.sleep(500); MessageProducer prod1 = session1.createProducer(topic1); prod1.setDeliveryMode(DeliveryMode.PERSISTENT); prod1.send(session1.createTextMessage("m1")); prod1.send(session1.createTextMessage("m2")); printBindings(jmsServer1.getActiveMQServer(), "jms.topic.t1"); printBindings(jmsServer2.getActiveMQServer(), "jms.topic.t1"); crash(); // this may or may not be closed, if the server was crashed then it would have been closed on // failure. cons2.close(); printBindings(jmsServer1.getActiveMQServer(), "jms.topic.t1"); // send a few messages while the binding is disconnected prod1.send(session1.createTextMessage("m3")); prod1.send(session1.createTextMessage("m4")); prod1.send(session1.createTextMessage("m5")); restart(); Thread.sleep(2000); printBindings(jmsServer1.getActiveMQServer(), "jms.topic.t1"); printBindings(jmsServer2.getActiveMQServer(), "jms.topic.t1"); prod1.send(session1.createTextMessage("m6")); prod1.send(session1.createTextMessage("m7")); TextMessage received = (TextMessage) cons1.receive(5000); assertNotNull(received); assertEquals("m1", received.getText()); received = (TextMessage) cons1.receive(5000); assertNotNull(received); assertEquals("m3", received.getText()); received = (TextMessage) cons1.receive(5000); assertNotNull(received); assertEquals("m4", received.getText()); received = (TextMessage) cons1.receive(5000); assertNotNull(received); assertEquals("m5", received.getText()); received = (TextMessage) cons1.receive(5000); assertNotNull(received); assertEquals("m6", received.getText()); received = (TextMessage) cons1.receive(5000); assertNotNull(received); assertEquals("m7", received.getText()); cons2.close(); } finally { conn1.close(); conn2.close(); } jmsServer1.destroyTopic("t1"); jmsServer2.destroyTopic("t1"); }