ITコンサルの日常

ITコンサル会社に勤務する普通のITエンジニアの日常です。

HornetQ Native APIでsendしてるのにreceiveできない場合

ソース

	public static void main(String[] args) throws Exception {
		ServerLocator serverLocator = null;
		ClientSessionFactory factory = null;
		ClientSession session = null;

		HashMap<String, Object> map = new HashMap<>();
		map.put("host", "localhost");
		map.put("port", 5445);

		TransportConfiguration configuration = new TransportConfiguration(NettyConnectorFactory.class.getName(), map);

		serverLocator = HornetQClient.createServerLocatorWithoutHA(configuration);
		factory = serverLocator.createSessionFactory();

		session = factory.createSession(false, false, false);
		session.start();
		ClientMessage message = session.createMessage(false);

		final String queueName = "jms.queue.ExampleQueue";
		ClientProducer producer = session.createProducer(queueName);

		for (int i = 0; i < 100; i++) {
			message.getBodyBuffer().clear();
			message.getBodyBuffer().writeString("new message sent at " + new Date());
			producer.send(message);
		}

		ClientConsumer consumer = session.createConsumer(queueName);
		System.out.println(consumer.receive(1000));
		
		session.close();
		factory.close();
		serverLocator.close();
	}

100メッセージをsendしているのに、その直後のreceiveでメッセージが取れずnullが表示されます。

原因

コミットしてない

session = factory.createSession(false, false, false);
  • xa - whether the session support XA transaction semantic or not
  • autoCommitSends - true to automatically commit message sends, false to commit manually
  • autoCommitAcks - true to automatically commit message acknowledgement, false to commit manually

対策

ということなので、第二引数と第三引数をtrueにするとオートコミットになって解決する。

session = factory.createSession(false, true, true);

もしくは、send後に、session.commit()を呼ぶ。

session.commit();