8.5.3. 使用 Core API 连接到服务器
您可以使用 Core API 进行客户端连接,而无需 JNDI 查找。使用核心 API 的客户端在其类路径中要求客户端 JAR,就像基于 JNDI 的客户端一样。
ServerLocator
客户端使用 ServerLocator
实例来创建 ClientSessionFactory
实例。顾名思义,ServerLocator
实例用于查找服务器并创建与服务器的连接。
在 JMS 术语中,考虑 ServerLocator
的方式与 JMS 连接事实相同。
ServerLocator
实例是使用 ActiveMQClient
工厂类创建的。
ServerLocator locator = ActiveMQClient.createServerLocatorWithoutHA(new TransportConfiguration(InVMConnectorFactory.class.getName()));
ClientSessionFactory
客户端使用 ClientSessionFactory
创建 客户端Session
实例,这些实例基本上是与服务器的连接。在 JMS 术语中,它们被视为 JMS 连接。
ClientSessionFactory
实例使用 ServerLocator
类创建。
ClientSessionFactory factory = locator.createClientSessionFactory();
ClientSession
客户端使用客户端 Session
来使用和生成消息,并将其分组到交易中。ClientSession
实例可以同时支持事务性和非事务性语义,还提供 XAResource 接口,以便消息传递操作可以作为 JTA 事务的一部分来执行。
ClientSession
Instance group ClientConsumers
和 ClientProducers
.
ClientSession session = factory.createSession();
以下简单示例重点介绍了刚刚讨论的一些内容:
ServerLocator locator = ActiveMQClient.createServerLocatorWithoutHA( new TransportConfiguration( InVMConnectorFactory.class.getName())); // In this simple example, we just use one session for both // producing and consuming ClientSessionFactory factory = locator.createClientSessionFactory(); ClientSession session = factory.createSession(); // A producer is associated with an address ... ClientProducer producer = session.createProducer("example"); ClientMessage message = session.createMessage(true); message.getBodyBuffer().writeString("Hello"); // We need a queue attached to the address ... session.createQueue("example", "example", true); // And a consumer attached to the queue ... ClientConsumer consumer = session.createConsumer("example"); // Once we have a queue, we can send the message ... producer.send(message); // We need to start the session before we can -receive- messages ... session.start(); ClientMessage msgReceived = consumer.receive(); System.out.println("message = " + msgReceived.getBodyBuffer().readString()); session.close();