HttpTunnelingServlet на JBoss AS 7 - PullRequest
       30

HttpTunnelingServlet на JBoss AS 7

1 голос
/ 03 апреля 2012

Пытаясь запустить Пример транспорта сервлета JMS в текущем выпуске JBoss (AS 7.1.1.), Я получаю "java.net.ConnectException: соединение отказано" в Channel.connect ().
Если в HttpTunnelingServlet я заменяю LocalAddress на InetSocketAddress, соединение работает, но мне интересно, является ли это правильным подходом.
Кроме того, я прочитал org.jboss.netty.channel.socket.http , но не знаю, как запустить его на JBoss AS 7.
Любой совет, как запустить HttpTunnelingServlet на JBoss AS 7, будет очень признателен.

Спасибо большое!


Клиент обмена сообщениями:

import java.util.Properties;

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 javax.naming.Context;
import javax.naming.InitialContext;


public class ServletTransportExample {
    public static void main(final String[] args) throws Exception {
        Connection connection = null;
        InitialContext initialContext = null;
        try {

            final Properties env = new Properties();
            env.put(Context.INITIAL_CONTEXT_FACTORY,
                    org.jboss.naming.remote.client.InitialContextFactory.class
                            .getName());
            env.put(Context.PROVIDER_URL, "remote://localhost:4447");
            env.put(Context.SECURITY_PRINCIPAL, "admin");
            env.put(Context.SECURITY_CREDENTIALS, "test");

            // Step 1. Create an initial context to perform the JNDI lookup.
            initialContext = new InitialContext(env);

            // Step 2. Perfom a lookup on the queue
            Queue queue = (Queue) initialContext.lookup("jms/queue/testQueue");

            // Step 3. Perform a lookup on the Connection Factory
            ConnectionFactory cf = (ConnectionFactory) initialContext
                    .lookup("jms/ServletConnectionFactory");

            // Step 4.Create a JMS Connection
            connection = cf.createConnection("admin", "test");

            System.out.println("connection created: " + connection);

            // 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());

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // Step 12. Be sure to close our JMS resources!
            if (initialContext != null) {
                initialContext.close();
            }
            if (connection != null) {
                connection.close();
            }
        }
    }

}

Web.xml туннельной войны:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:javaee="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4">
  <servlet>
    <servlet-name>HornetQServlet</servlet-name>
    <servlet-class>org.jboss.netty.channel.socket.http.HttpTunnelingServlet</servlet-class>
    <init-param>
      <javaee:param-name>endpoint</javaee:param-name>
      <javaee:param-value>local:org.hornetq</javaee:param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>HornetQServlet</servlet-name>
    <url-pattern>/HornetQServlet</url-pattern>
  </servlet-mapping>
</web-app>

Подсистема обмена сообщениями standalone-full.xml:

<subsystem xmlns="urn:jboss:domain:messaging:1.1">
    <hornetq-server>
        <persistence-enabled>true</persistence-enabled>
        <journal-file-size>102400</journal-file-size>
        <journal-min-files>2</journal-min-files>

        <connectors>
            <connector name="netty-servlet" socket-binding="http">
                <factory-class>org.hornetq.core.remoting.impl.netty.NettyConnectorFactory</factory-class>
                <param key="servlet-path" value="/messaging/HornetQServlet"/>
                <param key="host" value="localhost"/>
                <param key="use-servlet" value="true"/>
                <param key="http-enabled" value="true"/>
                <param key="port" value="8080"/>
            </connector>
            <netty-connector name="netty" socket-binding="messaging"/>
            <netty-connector name="netty-throughput" socket-binding="messaging-throughput">
                <param key="batch-delay" value="50"/>
            </netty-connector>
            <in-vm-connector name="in-vm" server-id="0"/>
        </connectors>

        <acceptors>
            <acceptor name="netty-servlet">
                <factory-class>org.hornetq.core.remoting.impl.netty.NettyAcceptorFactory</factory-class>
                <param key="use-invm" value="true"/>
                <param key="host" value="org.hornetq"/>
            </acceptor>
            <acceptor name="netty-invm">
                <factory-class>org.hornetq.core.remoting.impl.netty.NettyAcceptorFactory</factory-class>
                <param key="use-invm" value="true"/>
                <param key="host" value="org.hornetq"/>
            </acceptor>
            <netty-acceptor name="netty" socket-binding="messaging"/>
            <netty-acceptor name="netty-throughput" socket-binding="messaging-throughput">
                <param key="batch-delay" value="50"/>
                <param key="direct-deliver" value="false"/>
            </netty-acceptor>
            <in-vm-acceptor name="in-vm" server-id="0"/>
        </acceptors>

        <security-settings>
            <security-setting match="#">
                <permission type="send" roles="guest"/>
                <permission type="consume" roles="guest"/>
                <permission type="createNonDurableQueue" roles="guest"/>
                <permission type="deleteNonDurableQueue" roles="guest"/>
            </security-setting>
        </security-settings>

        <address-settings>
            <address-setting match="#">
                <dead-letter-address>jms.queue.DLQ</dead-letter-address>
                <expiry-address>jms.queue.ExpiryQueue</expiry-address>
                <redelivery-delay>0</redelivery-delay>
                <max-size-bytes>10485760</max-size-bytes>
                <address-full-policy>BLOCK</address-full-policy>
                <message-counter-history-day-limit>10</message-counter-history-day-limit>
            </address-setting>
        </address-settings>

        <jms-connection-factories>
            <connection-factory name="ServletConnectionFactory">
                <connectors>
                    <connector-ref connector-name="netty-servlet"/>
                </connectors>
                <entries>
                    <entry name="ServletConnectionFactory"/>
                    <entry name="java:jboss/exported/jms/ServletConnectionFactory"/>
                </entries>
            </connection-factory>
            <connection-factory name="InVmConnectionFactory">
                <connectors>
                    <connector-ref connector-name="in-vm"/>
                </connectors>
                <entries>
                    <entry name="java:/ConnectionFactory"/>
                </entries>
            </connection-factory>
            <connection-factory name="RemoteConnectionFactory">
                <connectors>
                    <connector-ref connector-name="netty"/>
                </connectors>
                <entries>
                    <entry name="RemoteConnectionFactory"/>
                    <entry name="java:jboss/exported/jms/RemoteConnectionFactory"/>
                </entries>
            </connection-factory>
            <pooled-connection-factory name="hornetq-ra">
                <transaction mode="xa"/>
                <connectors>
                    <connector-ref connector-name="in-vm"/>
                </connectors>
                <entries>
                    <entry name="java:/JmsXA"/>
                </entries>
            </pooled-connection-factory>
        </jms-connection-factories>

        <jms-destinations>
            <jms-queue name="testQueue">
                <entry name="/queue/testQueue"/>
                <entry name="java:jboss/exported/jms/queue/testQueue"/>
            </jms-queue>
        </jms-destinations>
    </hornetq-server>
</subsystem>

Трассировка стека:

13: 31: 29,747 WARN [org.jboss.netty.channel.socket.http.HttpTunnelingServlet] (http - 127.0.0.1-8080-1) Конечная точка недоступна: соединение отклонено: java.net.ConnectException: соединение отказано
в org.jboss.netty.channel.local.LocalClientChannelSink.connect (LocalClientChannelSink.java:113) [netty-3.2.6.Final.jar:]
в org.jboss.netty.channel.local.LocalClientChannelSink.eventSunk (LocalClientChannelSink.java:73) [netty-3.2.6.Final.jar:]
на org.jboss.netty.channel.Channels.connect (Channels.java:541) [netty-3.2.6.Final.jar:]
в org.jboss.netty.channel.AbstractChannel.connect (AbstractChannel.java:210) [netty-3.2.6.Final.jar:]
в org.jboss.netty.channel.socket.http.HttpTunnelingServlet.service (HttpTunnelingServlet.java:150) [netty-3.2.6.Final.jar:]
в javax.servlet.http.HttpServlet.service (HttpServlet.java:847) [jboss-servlet-api_3.0_spec-1.0.0.Final.jar: 1.0.0.Final]
в org.apache.catalina.core.ApplicationFilterChain.internalDoFilter (ApplicationFilterChain.java:329) [jbossweb-7.0.13.Final.jar:]
в org.apache.catalina.core.ApplicationFilterChain.doFilter (ApplicationFilterChain.java:248) [jbossweb-7.0.13.Final.jar:]
в org.apache.catalina.core.StandardWrapperValve.invoke (StandardWrapperValve.java:275) [jbossweb-7.0.13.Final.jar:]
в org.apache.catalina.core.StandardContextValve.invoke (StandardContextValve.java:161) [jbossweb-7.0.13.Final.jar:]
в org.jboss.as.web.security.SecurityContextAssociationValve.invoke (SecurityContextAssociationValve.java:153) [jboss-as-web-7.1.1.Final.jar: 7.1.1.Final]
в org.apache.catalina.core.StandardHostValve.invoke (StandardHostValve.java:155) [jbossweb-7.0.13.Final.jar:]
в org.apache.catalina.valves.ErrorReportValve.invoke (ErrorReportValve.java:102) [jbossweb-7.0.13.Final.jar:]
в org.apache.catalina.core.StandardEngineValve.invoke (StandardEngineValve.java:109) [jbossweb-7.0.13.Final.jar:]
в org.apache.catalina.connector.CoyoteAdapter.service (CoyoteAdapter.java:368) [jbossweb-7.0.13.Final.jar:]
в org.apache.coyote.http11.Http11Processor.process (Http11Processor.java:877) [jbossweb-7.0.13.Final.jar:]
в org.apache.coyote.http11.Http11Protocol $ Http11ConnectionHandler.process (Http11Protocol.java:671) [jbossweb-7.0.13.Final.jar:]
в org.apache.tomcat.util.net.JIoEndpoint $ Worker.run (JIoEndpoint.java:930) [jbossweb-7.0.13.Final.jar:]
at java.lang.Thread.run (Thread.java:662) [rt.jar: 1.6.0_22]

Ответы [ 4 ]

2 голосов
/ 06 августа 2012

Возможно, вы преодолели свою проблему, но если нет, я получил точно такую ​​же ошибку, но сумел ее устранить, как только добавил определение акцептора;то есть netty-invm, как вы определили выше.

        <connectors>
            <netty-connector name="netty" socket-binding="messaging"/>
            <netty-connector name="netty-throughput" socket-binding="messaging-throughput">
                <param key="batch-delay" value="50"/>
            </netty-connector>
            <netty-connector name="netty-servlet" socket-binding="http">
                <param key="host" value="${jboss.bind.address}"/>
                <param key="use-servlet" value="true"/>
                <param key="servlet-path" value="/hornetq-servlet/HornetQServlet"/>
            </netty-connector>
            <in-vm-connector name="in-vm" server-id="0"/>
        </connectors>

        <acceptors>
            <netty-acceptor name="netty" socket-binding="messaging"/>
            <netty-acceptor name="netty-throughput" socket-binding="messaging-throughput">
                <param key="batch-delay" value="50"/>
                <param key="direct-deliver" value="false"/>
            </netty-acceptor>
                <acceptor name="netty-invm">
                    <factory-class>
                      org.hornetq.core.remoting.impl.netty.NettyAcceptorFactory
                    </factory-class>
                    <param key="use-invm" value="true"/>
                    <param key="host" value="org.hornetq"/>
                </acceptor>
                <in-vm-acceptor name="in-vm" server-id="0"/>
        </acceptors>

Я не верю, что вам нужен параметр атрибута с поддержкой http, а также вам нужен только один получатель, который пересылает сообщения на входРазъем -vm, так что приемник netty-servlet может идти.

Следующая проблема, с которой я сталкиваюсь, это следующее исключение при отправке сообщения

2012-08-06 18:09:54,557 ERROR [org.apache.catalina.connector.CoyoteAdapter](http-executor-threads - 2) An exception or error occurred in the container during the request processing: java.lang.IllegalStateException: JBAS018053: No security context found
    at org.jboss.as.web.security.SecurityActions$6.run(SecurityActions.java:136)
    at org.jboss.as.web.security.SecurityActions$6.run(SecurityActions.java:130)
    at java.security.AccessController.doPrivileged(Native Method)
    at org.jboss.as.web.security.SecurityActions.popRunAsIdentity(SecurityActions.java:130)
    at org.jboss.as.web.security.SecurityContextAssociationValve.invoke(SecurityContextAssociationValve.java:155)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:155)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:567)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:368)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:877)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:671)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:518)
    at org.jboss.threads.SimpleDirectExecutor.execute(SimpleDirectExecutor.java:33)
    at org.jboss.threads.QueueExecutor.runTask(QueueExecutor.java:801)
    at org.jboss.threads.QueueExecutor.access$100(QueueExecutor.java:45)
    at org.jboss.threads.QueueExecutor$Worker.run(QueueExecutor.java:821)
    at java.lang.Thread.run(Thread.java:662)
    at org.jboss.threads.JBossThread.run(JBossThread.java:122)

Я ищу следующую часть в этой темеhttps://community.jboss.org/message/752593

0 голосов
/ 09 декабря 2015

Все настройки в приведенных выше ответах верны, но вам также необходимо добавить требуемую зависимость Netty, например:

MANIFEST.MF

Dependencies: org.jboss.netty

jboss-deployement-structure.xml

<jboss-deployment-structure>
    <deployment>
        <dependencies>
            <module name="org.jboss.netty" />
        </dependencies>
    </deployment>
</jboss-deployment-structure>

Надеясь, что это кому-нибудь поможет.

0 голосов
/ 13 мая 2015

Это у меня работает.

Сервер с акцептором

        <subsystem xmlns="urn:jboss:domain:messaging:1.3">
            <hornetq-server>
                <persistence-enabled>true</persistence-enabled>

                <cluster-user>jms-user</cluster-user>
                <cluster-password>12345678</cluster-password>

                <connectors>
                    <netty-connector name="netty" socket-binding="messaging" />
                    <in-vm-connector name="in-vm" server-id="0" />
                </connectors>

                <acceptors>
                    <netty-acceptor name="netty" socket-binding="messaging" />
                    <in-vm-acceptor name="in-vm" server-id="0" />

                    <acceptor name="netty-servlet">
                        <factory-class>org.hornetq.core.remoting.impl.netty.NettyAcceptorFactory</factory-class>
                        <param key="use-invm" value="true"/>
                        <param key="host" value="org.hornetq"/>
                    </acceptor>

                </acceptors>

                <security-settings>
                    <security-setting match="#">
                        <permission type="send" roles="queueSend" />
                        <permission type="consume" roles="queueConsume" />
                        <permission type="createNonDurableQueue" roles="queueMngNonDurable" />
                        <permission type="deleteNonDurableQueue" roles="queueMngNonDurable" />
                    </security-setting>
                </security-settings>

                <address-settings>
                    <address-setting match="#">
                        <dead-letter-address>jms.queue.DLQ</dead-letter-address>
                        <expiry-address>jms.queue.ExpiryQueue</expiry-address>
                        <redelivery-delay>1000</redelivery-delay>
                        <max-delivery-attempts>3</max-delivery-attempts>
                        <redistribution-delay>1000</redistribution-delay>
                        <message-counter-history-day-limit>30</message-counter-history-day-limit>
                    </address-setting>
                </address-settings>

                <jms-connection-factories>
                    <pooled-connection-factory name="hornetq-ra">
                        <transaction mode="xa" />
                        <connectors>
                            <connector-ref connector-name="in-vm" />
                        </connectors>
                        <entries>
                            <entry name="java:/JmsXA" />
                            <entry name="java:/ConnectionFactory" />
                        </entries>

                        <!-- Cluster credential -->
                        <user>jms-user</user>
                        <password>12345678</password>
                    </pooled-connection-factory>

                </jms-connection-factories>

                <jms-destinations>

                    <jms-topic name="topic/sample_update_data">
                        <entry name="topic/sample_update_data" />
                        <entry name="jboss/exported/topic/sample_update_data" />
                    </jms-topic>

                </jms-destinations>
            </hornetq-server>
        </subsystem>

Сервер с разъемом

    <subsystem xmlns="urn:jboss:domain:messaging:1.3">
        <hornetq-server>
            <persistence-enabled>true</persistence-enabled>

            <connectors>
                <netty-connector name="netty" socket-binding="messaging"/>
                <netty-connector name="netty-servlet" socket-binding="external-messaging">
                    <param key="use-servlet" value="true"/>
                    <param key="servlet-path" value="/mcc-hornetq/HornetQServlet"/>
                </netty-connector>
                <in-vm-connector name="in-vm" server-id="0"/>
            </connectors>

            <acceptors>
                <netty-acceptor name="netty" socket-binding="messaging"/>
                <in-vm-acceptor name="in-vm" server-id="0"/>
            </acceptors>

            <security-settings>
                <security-setting match="#">
                    <permission type="send" roles="queueSend"/>
                    <permission type="consume" roles="queueConsume"/>
                    <permission type="createNonDurableQueue" roles="queueMngNonDurable"/>
                    <permission type="deleteNonDurableQueue" roles="queueMngNonDurable"/>
                </security-setting>
            </security-settings>

            <address-settings>
                <address-setting match="#">
                    <dead-letter-address>jms.queue.DLQ</dead-letter-address>
                    <expiry-address>jms.queue.ExpiryQueue</expiry-address>
                    <redelivery-delay>30000</redelivery-delay>
                    <max-delivery-attempts>1</max-delivery-attempts>
                    <message-counter-history-day-limit>30</message-counter-history-day-limit>
                </address-setting>
            </address-settings>

            <jms-connection-factories>
                <pooled-connection-factory name="hornetq-ra">
                    <transaction mode="xa"/>
                    <connectors>
                        <connector-ref connector-name="in-vm"/>
                    </connectors>
                    <entries>
                        <entry name="java:/JmsXA"/>
                        <entry name="java:/ConnectionFactory"/>
                    </entries>
                </pooled-connection-factory>
                <pooled-connection-factory name="external-hornetq-ra">
                    <transaction mode="xa"/>
                    <user>jms-user</user>
                    <password>12345678</password>
                    <connectors>
                        <connector-ref connector-name="netty-servlet"/>
                    </connectors>
                    <entries>
                        <entry name="java:/JmsXA_External"/>
                    </entries>
                    <client-failure-check-period>5000</client-failure-check-period>
                    <retry-interval>2000</retry-interval>
                    <retry-interval-multiplier>1.5</retry-interval-multiplier>
                    <max-retry-interval>60000</max-retry-interval>
                    <reconnect-attempts>10</reconnect-attempts>
                </pooled-connection-factory>
            </jms-connection-factories>

            <jms-destinations>
                <jms-queue name="queue/another_data">
                    <entry name="queue/another_data"/>
                </jms-queue>
            </jms-destinations>
        </hornetq-server>
    </subsystem>


    ....


    <outbound-socket-binding name="external-messaging">
        <remote-destination host="192.168.2.58" port="8080" />
    </outbound-socket-binding>

и MDB на внешнем сервере

@MessageDriven(activationConfig = { 
        @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Topic"),
        @ActivationConfigProperty(propertyName = "destination", propertyValue = "topic/sample_data"),
        @ActivationConfigProperty(propertyName = "subscriptionName", propertyValue = "update-data"),
        @ActivationConfigProperty(propertyName = "hA", propertyValue =  "true"),
        @ActivationConfigProperty(propertyName = "shareSubscriptions", propertyValue = "true"),     
    })
@ResourceAdapter(value = "external-hornetq-ra")
public class UpdateCacheMDB implements MessageListener {

    @Override
    public void onMessage(Message message) {
        ObjectMessage objMsg = (ObjectMessage) message;
    }

}
0 голосов
/ 16 апреля 2012

Попробуйте что-то вроде

ConnectionFactory cf = (ConnectionFactory) ic.lookup("/ConnectionFactory");
Queue q = (Queue) ic.lookup("/queue/testQueue");

и я не знаю, какой тип пользователя jboss «admin», это должен быть пользователь приложения. Не забудьте включить jboss jar.

...