连接到JMS服务器的HornetQ。

时间:2021-07-25 02:44:08

I am currently trying to create a JMS client for a JMS Server both using HornetQ. I did not code the server and I don't know much about hoy it works, I only know how to connect to it: no username, no password and the address is jnp://x.y.z.t:1099 .

我目前正在尝试为一个使用HornetQ的JMS服务器创建JMS客户机。我没有编码服务器,我也不知道它的工作原理,我只知道如何连接它:没有用户名,没有密码,地址是jnp://x.y.z。t:1099。

I am trying to connect to the server without using JNDI and I am having some trouble. In fact I have found this example: http://anonsvn.jboss.org/repos/hornetq/trunk/examples/jms/instantiate-connection-factory/ and I don't know what do I need to change in the XML files and in the code to make it work.

我尝试连接到服务器而不使用JNDI,我遇到了一些麻烦。实际上,我已经找到了这个示例:http://anonsvn.jboss.org/repos/hornetq/trunk/examples/jms/instanticonnectionfactory/,我不知道在XML文件和代码中需要更改什么,才能使其工作。

I had this code, with JNDI:

我有这个代码,JNDI:

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * A simple polymorphic JMS producer which can work with Queues or Topics which
 * uses JNDI to lookup the JMS connection factory and destination
 * 
 * 
 */
public final class SimpleProducer {

    private static final Logger LOG = LoggerFactory.getLogger(SimpleProducer.class);

    private SimpleProducer() {
    }

    /**
     * @param args the destination name to send to and optionally, the number of
     *                messages to send
     */
    public static void main(String[] args) {
        Context jndiContext = null;
        ConnectionFactory connectionFactory = null;
        Connection connection = null;
        Session session = null;
        Destination destination = null;
        MessageProducer producer = null;
        String destinationName = null;
        final int numMsgs;

        if ((args.length < 1) || (args.length > 2)) {
            LOG.info("Usage: java SimpleProducer <destination-name> [<number-of-messages>]");
            System.exit(1);
        }
        destinationName = args[0];
        LOG.info("Destination name is " + destinationName);
        if (args.length == 2) {
            numMsgs = (new Integer(args[1])).intValue();
        } else {
            numMsgs = 1;
        }

        /*
         * Create a JNDI API InitialContext object
         */
        try {
            jndiContext = new InitialContext();
        } catch (NamingException e) {
            LOG.info("Could not create JNDI API context: " + e.toString());
            System.exit(1);
        }

        /*
         * Look up connection factory and destination.
         */
        try {
            connectionFactory = (ConnectionFactory)jndiContext.lookup("ConnectionFactory");
            destination = (Destination)jndiContext.lookup(destinationName);
        } catch (NamingException e) {
            LOG.info("JNDI API lookup failed: " + e);
            System.exit(1);
        }

        /*
         * Create connection. Create session from connection; false means
         * session is not transacted. Create sender and text message. Send
         * messages, varying text slightly. Send end-of-messages message.
         * Finally, close connection.
         */
        try {
            connection = connectionFactory.createConnection();
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            producer = session.createProducer(destination);
            TextMessage message = session.createTextMessage();
            for (int i = 0; i < numMsgs; i++) {
                message.setText("This is message " + (i + 1));
                LOG.info("Sending message: " + message.getText());
                producer.send(message);
            }

            /*
             * Send a non-text control message indicating end of messages.
             */
            producer.send(session.createMessage());
        } catch (JMSException e) {
            LOG.info("Exception occurred: " + e);
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (JMSException e) {
                }
            }
        }
    }
}

with this jndi.properties file:

jndi。属性文件:

java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory
java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces
java.naming.provider.url = jnp://x.y.z.t:1099

and everything worked fine. But now I need to do the same thing without JNDI. The example I gave above (http://anonsvn.jboss.org/repos/hornetq/trunk/examples/jms/instantiate-connection-factory/) shoutd work, but I don't know what to change in the config to make it work, I have never used a JMS client this way, so I'm completelly lost!

和一切工作正常。但是现在我需要在没有JNDI的情况下做同样的事情。我在上面给出的例子(http://anonsvn.jboss.org/repos/hornetq/trunk/examples/jms/instance - connectionfactory/) shoutd工作,但是我不知道在配置中要更改什么以使其工作,我从来没有这样使用JMS客户机,所以我完全失败了!

These are the config files I'm talking about: http://anonsvn.jboss.org/repos/hornetq/trunk/examples/jms/instantiate-connection-factory/server0/ . I coulnd't find on the net to what the files correpsond, I'm confused. Also, the Java code is here: http://anonsvn.jboss.org/repos/hornetq/trunk/examples/jms/instantiate-connection-factory/src/org/hornetq/jms/example/InstantiateConnectionFactoryExample.java

这些是我正在讨论的配置文件:http://anonsvn.jboss.org/repos/hornetq/trunk/examples/jms/instance - connectionfactory/server0/。我在网上找不到有关文件的内容,我很困惑。同样,Java代码也在这里:http://anonsvn.jboss.org/repos/hornetq/trunk/examples/jms/instanticonnectionfactory/src/org/hornet/example/example/instantiateconnectionfactoryexample.java。

Thank you in advance

提前谢谢你

----- EDIT This is the last vesion of my code:

---编辑这是我的代码的最后一个vesion:

import java.util.HashMap;
import java.util.Map;


import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;


import org.hornetq.api.core.TransportConfiguration;
import org.hornetq.api.jms.HornetQJMSClient;
import org.hornetq.api.jms.JMSFactoryType;
import org.hornetq.common.example.HornetQExample;
import org.hornetq.core.remoting.impl.netty.NettyConnectorFactory;
import org.hornetq.core.remoting.impl.netty.TransportConstants;
import org.hornetq.jms.client.HornetQConnectionFactory;


public class Snippet extends HornetQExample
{
   public static void main(final String[] args)
   {
      new Snippet().run(args);
   }


   @Override
   public boolean runExample() throws Exception
   {
      Connection connection = null;
      try
      {
         // Step 1. Directly instantiate the JMS Queue object.
         Queue queue = HornetQJMSClient.createQueue("exampleQueue");


         // Step 2. Instantiate the TransportConfiguration object which contains the knowledge of what transport to use,
         // The server port etc.


         Map<String, Object> connectionParams = new HashMap<String, Object>();
         connectionParams.put(TransportConstants.PORT_PROP_NAME, 5446);
         //My server's port:
         //connectionParams.put(TransportConstants.PORT_PROP_NAME, 1099);


         TransportConfiguration transportConfiguration = new TransportConfiguration(NettyConnectorFactory.class.getName(),
                                                                                    connectionParams);


         // Step 3 Directly instantiate the JMS ConnectionFactory object using that TransportConfiguration
         HornetQConnectionFactory cf = HornetQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, transportConfiguration);


         // Step 4.Create a JMS Connection
         connection = cf.createConnection();

         // Step 5. Create a JMS Session
         Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);


         // Step 6. Create a JMS Message Producer
         MessageProducer producer = session.createProducer(queue);


         // Step 7. Create a Text Message
         TextMessage message = session.createTextMessage("This is a text message");


         System.out.println("Sent message: " + message.getText());


         // Step 8. Send the Message
         producer.send(message);


         // Step 9. Create a JMS Message Consumer
         MessageConsumer messageConsumer = session.createConsumer(queue);


         // Step 10. Start the Connection
         connection.start();


         // Step 11. Receive the message
         TextMessage messageReceived = (TextMessage)messageConsumer.receive(5000);


         System.out.println("Received message: " + messageReceived.getText());


         return true;
      }
      finally
      {
         if (connection != null)
         {
            connection.close();
         }
      }
   }


}

This is my hornetq-beans.xml (I disable JNDI)

这是我的hornetq-beans。xml(我禁用JNDI)

<?xml version="1.0" encoding="UTF-8"?>


<deployment xmlns="urn:jboss:bean-deployer:2.0">


   <bean name="Naming" class="org.jnp.server.NamingBeanImpl"/>


   <!-- JNDI server. Disable this if you don't want JNDI -->
   <!-- <bean name="JNDIServer" class="org.jnp.server.Main">
      <property name="namingInfo">
         <inject bean="Naming"/>
      </property>
      <property name="port">1099</property>
                                                                            <!-- <property name="bindAddress">localhost</property>
      <property name="bindAddress">jnp://X.Y.Z.T</property>
      <property name="rmiPort">1098</property>
                                                                            <!-- <property name="rmiBindAddress">localhost</property>
      <property name="bindAddress">jnp://X.Y.Z.T</property>
   </bean>-->

   <!-- MBean server -->
   <bean name="MBeanServer" class="javax.management.MBeanServer">
      <constructor factoryClass="java.lang.management.ManagementFactory"
                   factoryMethod="getPlatformMBeanServer"/>
   </bean> 


   <!-- The core configuration -->
   <bean name="Configuration" class="org.hornetq.core.config.impl.FileConfiguration"/>


   <!-- The security manager -->
   <bean name="HornetQSecurityManager" class="org.hornetq.spi.core.security.HornetQSecurityManagerImpl">
      <start ignored="true"/>
      <stop ignored="true"/>
   </bean>


   <!-- The core server -->
   <bean name="HornetQServer" class="org.hornetq.core.server.impl.HornetQServerImpl">
      <constructor>
         <parameter>
            <inject bean="Configuration"/>
         </parameter>
         <parameter>
            <inject bean="MBeanServer"/>
         </parameter>
         <parameter>
            <inject bean="HornetQSecurityManager"/>
         </parameter>        
      </constructor>
      <start ignored="true"/>
      <stop ignored="true"/>
   </bean>

   <!-- The JMS server -->
   <bean name="JMSServerManager" class="org.hornetq.jms.server.impl.JMSServerManagerImpl">
      <constructor>         
         <parameter>
            <inject bean="HornetQServer"/>
         </parameter>
      </constructor>
   </bean>


</deployment>

and my hornetq-jms.xml (same as in the example)

和我的hornetq-jms。xml(与示例中相同)

<configuration xmlns="urn:hornetq"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:schemaLocation="urn:hornetq /schema/hornetq-jms.xsd">

   <!--the queue used by the example-->
   <queue name="exampleQueue">
      <entry name="/queue/exampleQueue"/>
   </queue>


</configuration>

hornetq-users.xml (There is no need to have users to connect to the JMS server, so I commented it):

hornetq-users。xml(不需要用户连接到JMS服务器,所以我注释了它):

<configuration xmlns="urn:hornetq" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:schemaLocation="urn:hornetq /schema/hornetq-users.xsd">
   <!-- the default user.  this is used where username is null
   <defaultuser name="guest" password="guest">
      <role name="guest"/>
   </defaultuser>-->
</configuration> 

My hornetq-configuratio.xml: I am not sur whether I have to put jnp:// in the connectors and acceptors or not. Actually I don't really get much of this....

我的hornetq-configuratio。xml:我不知道是否需要将jnp://在连接器和接受器中。实际上我并没有得到很多

<configuration xmlns="urn:hornetq"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:schemaLocation="urn:hornetq /schema/hornetq-configuration.xsd">


   <!-- Connectors -->


   <connectors>
      <connector name="netty-connector">
         <factory-class>org.hornetq.core.remoting.impl.netty.NettyConnectorFactory</factory-class>
         <param key="host" value="jnp://X.Y.Z.T"/>    
         <param key="port" value="5445"/>
      </connector>
   </connectors>

   <!-- Acceptors -->
   <acceptors>
      <acceptor name="netty-acceptor">
         <factory-class>org.hornetq.core.remoting.impl.netty.NettyAcceptorFactory</factory-class>         
         <param key="host" value="jnp://X.Y.Z.T"/>
         <param key="port" value="5445"/>
      </acceptor>
   </acceptors>


   <!-- Other config -->


   <security-settings>
      <!--security for example queue-->
      <security-setting match="jms.queue.exampleQueue">
         <permission type="createDurableQueue" roles="guest"/>
         <permission type="deleteDurableQueue" roles="guest"/>
         <permission type="createNonDurableQueue" roles="guest"/>
         <permission type="deleteNonDurableQueue" roles="guest"/>
         <permission type="consume" roles="guest"/>
         <permission type="send" roles="guest"/>
      </security-setting>
   </security-settings>


</configuration>

What I get with this code is:

我得到的代码是:

HornetQException[errorCode=2 message=Cannot connect to server(s). Tried with all available servers.]
        at org.hornetq.core.client.impl.ServerLocatorImpl.createSessionFactory(ServerLocatorImpl.java:619)
        at org.hornetq.jms.client.HornetQConnectionFactory.createConnectionInternal(HornetQConnectionFactory.java:601)

I am using version 2.2.2, by the way ;)

顺便说一下,我使用的是2.2.2版;

1 个解决方案

#1


1  

If you want to use HornetQ's native client, look at these documents

如果您想使用HornetQ的本机客户端,请查看这些文档。

http://docs.jboss.org/hornetq/2.2.2.Final/user-manual/en/html_single/#d0e1611

http://docs.jboss.org/hornetq/2.2.2.Final/user-manual/en/html_single/ d0e1611

This will likely also help, with direct connections

这可能也会有帮助,有直接的联系。

http://docs.jboss.org/hornetq/2.2.2.Final/user-manual/en/html_single/#d0e2387

http://docs.jboss.org/hornetq/2.2.2.Final/user-manual/en/html_single/ d0e2387

You'll want to use their local core client examples.

您将希望使用它们的本地核心客户端示例。

#1


1  

If you want to use HornetQ's native client, look at these documents

如果您想使用HornetQ的本机客户端,请查看这些文档。

http://docs.jboss.org/hornetq/2.2.2.Final/user-manual/en/html_single/#d0e1611

http://docs.jboss.org/hornetq/2.2.2.Final/user-manual/en/html_single/ d0e1611

This will likely also help, with direct connections

这可能也会有帮助,有直接的联系。

http://docs.jboss.org/hornetq/2.2.2.Final/user-manual/en/html_single/#d0e2387

http://docs.jboss.org/hornetq/2.2.2.Final/user-manual/en/html_single/ d0e2387

You'll want to use their local core client examples.

您将希望使用它们的本地核心客户端示例。