Broker A-MQ embedded (Resource Adapter) no JBoss EAP

Network Connector VM

O conector de transporte do tipo vm:// é usado por aplicativos Java para executar um broker embedded e se conectar a ele. Nenhuma conexão de redes é utilizada neste caso, então a comunicação entre cliente e broker acontece através de invocações de método diretamente, aumentando a performance significamente. O broker é iniciado quando a primeira conexão usando o protocolo VM é criada e as próximas conexões vindas da mesma JVM irão se conectar ao mesmo broker. Quando todas as conexões VM ao broker forem fechadas, o broker embedded será desligado automaticamente.

webconsole

Configuração do JBoss EAP 6.1

1) Baixe o JBoss EAP 6.1 diretamente do site.

2) Descompacte-o num local de sua preferência. No meu caso utilizei o /opt.

3) Edite o arquivo /opt/jboss-eap-6.1/standalone/configuration/standalone-full.xml adicionando o seguinte trecho no perfil <subsystem xmlns=”urn:jboss:domain:resource-adapters:1.1″> :

<subsystem xmlns=”urn:jboss:domain:resource-adapters:1.1″>
<resource-adapters>
<resource-adapter id=”activemq-rar-5.8.0.rar”>
<archive>
activemq-rar-5.8.0.rar
</archive>
<transaction-support>XATransaction</transaction-support>
<config-property name=”UseInboundSession”>
false
</config-property>
<config-property name=”Password”>
defaultPassword
</config-property>
<config-property name=”UserName”>
defaultUser
</config-property>
<config-property name=”ServerUrl”>
vm://localhost
</config-property>
<connection-definitions>
<connection-definition class-name=”org.apache.activemq.ra.ActiveMQManagedConnectionFactory” jndi-name=”java:jboss/ConnectionFactory” enabled=”true” pool-name=”ConnectionFactory”>
<xa-pool>
<min-pool-size>1</min-pool-size>
<max-pool-size>20</max-pool-size>
</xa-pool>
</connection-definition>
</connection-definitions>
<admin-objects>
<admin-object class-name=”org.apache.activemq.command.ActiveMQQueue” jndi-name=”java:jboss/queue/MyActiveMQQueue” use-java-context=”true” pool-name=”MyActiveMQQueue”>
<config-property name=”PhysicalName”>
QueuePhysicalName
</config-property>
</admin-object>
</admin-objects>
</resource-adapter>
</resource-adapters>
</subsystem>

Configuração do ActiveMQ Resource Adapter

1) Baixe o JBoss A-MQ diretamente do site.

O resource adapter está escondido em: extras/apache-activemq-5.8.0.redhat-60024-bin.zip/lib/optional/activemq-rar-5.8.0.redhat-60024.rar

Obs: altere a extensão de activemq-rar-5.8.0.redhat-60024.rar para activemq-rar-5.8.0.redhat-60024.zip e descompacte-o.

2) Depois de extrair o resource adapter substitua o corpo do arquivo broker-config.xml com o seguinte conteúdo:

<?xml version=”1.0″ encoding=”UTF-8″?>

<beans
xmlns=”http://www.springframework.org/schema/beans&#8221;
xmlns:amq=”http://activemq.apache.org/schema/core&#8221;
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221;
xsi:schemaLocation=”http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core.xsd”&gt;

<!– Embedded – load configuration file from classpath –>
<bean class=”org.springframework.beans.factory.config.PropertyPlaceholderConfigurer”/>

<!– shutdown hook is disabled as RAR classloader may be gone at shutdown –>
<!– Embedded – Name the broker –>
<broker xmlns=”http://activemq.apache.org/schema/core&#8221; useJmx=”true” brokerName=”JBoss.Embedded” useShutdownHook=”false”>

<managementContext>
<!– use appserver provided context instead of creating one,  for jboss use: -Djboss.platform.mbeanserver –>
<managementContext createConnector=”false”/>
</managementContext>

<persistenceAdapter>
<!– Embedded – Use the server data directory for the broker database –>
<kahaDB directory=”${jboss.server.data.dir}/kahadb”/>
</persistenceAdapter>

<transportConnectors>
<!– Embedded – The embeded broker uses the in-JVM transport, and a NIO transport is also provided.
The “nio” below may be changed – use TCP, bind to just one interface, etc..
–>
<transportConnector name=”JBoss.Embedded” uri=”vm://localhost”/>
<transportConnector name=”nio” uri=”nio://0.0.0.0:61616″/>
</transportConnectors>

</broker>
</beans>

3) No arquivo META-INF/ra.xml procure a linha e descomente:

<config-property-value>tcp://localhost:61616</config-property-value>

Em seguida, descomente a linha:

<!–config-property-value>vm://localhost</config-property-value–>

Resultado:

<!– config-property-value>tcp://localhost:61616</config-property-value –>
<config-property-value>vm://localhost</config-property-value>

4) Remova as seguintes libs do resource adapter para não haver conflito com as já existentes no EAP:

  • slf4j-api-1.6.6.jar
  • slf4j-log4j12-1.6.6.jar

5) Depois de tudo alterado, compacte o arquivo .zip e renomeie-o para activemq-rar-5.8.0.rar e o mova para /opt/jboss-eap-6.1/standalone/deployments/

Inicialização do JBoss EAP 6.1   

Neste ponto temos o JBoss EAP 6.1 com o resource adapter configurado e copiado para a pasta deployments. Para inicializá-lo com o perfil customizado execute o seguinte comando na pasta a /opt/jboss-eap-6.1/bin: 

./standalone.sh -c standalone-full.xml

Console 

19:07:35,582 INFO [org.jboss.as.messaging] (ServerService Thread Pool — 58) JBAS011601: Bound messaging object to jndi name java:/ConnectionFactory
19:07:35,583 INFO [org.jboss.as.messaging] (ServerService Thread Pool — 59) JBAS011601: Bound messaging object to jndi name java:jboss/exported/jms/RemoteConnectionFactory
19:07:35,632 INFO [org.jboss.as.connector.deployment] (MSC service thread 1-7) JBAS010406: Registered connection factory java:/JmsXA
19:07:35,666 INFO [org.hornetq.ra] (MSC service thread 1-7) HornetQ resource adaptor started
19:07:35,667 INFO [org.jboss.as.connector.services.resourceadapters.ResourceAdapterActivatorService$ResourceAdapterActivator] (MSC service thread 1-7) IJ020002: Deployed: file://RaActivatorhornetq-ra
19:07:35,670 INFO [org.jboss.as.connector.deployment] (MSC service thread 1-2) JBAS010401: Bound JCA ConnectionFactory [java:/JmsXA]
19:07:35,830 INFO [org.jboss.as] (Controller Boot Thread) JBAS015961: Http management interface listening on http://127.0.0.1:9990/management
19:07:35,831 INFO [org.jboss.as] (Controller Boot Thread) JBAS015951: Admin console listening on http://127.0.0.1:9990
19:07:35,831 INFO [org.jboss.as] (Controller Boot Thread) JBAS015874: JBoss EAP 6.1.0.GA (AS 7.2.0.Final-redhat-8) started in 3487ms – Started 154 of 216 services (61 services are passive or on-demand)
19:08:25,127 INFO [org.jboss.as.server.deployment] (MSC service thread 1-4) JBAS015876: Starting deployment of “activemq-rar-5.8.0.rar” (runtime-name: “activemq-rar-5.8.0.rar”)
19:08:25,892 INFO [org.jboss.as.connector.deployers.RADeployer] (MSC service thread 1-2) IJ020001: Required license terms for file:/opt/jboss-eap-6.1/standalone/tmp/vfs/temp188ec44f68d80f15/activemq-rar-5.8.0.rar-12de4b0407eb87cc/contents/
19:08:25,923 INFO [org.jboss.as.connector.deployers.RaXmlDeployer] (MSC service thread 1-5) IJ020001: Required license terms for file:/opt/jboss-eap-6.1/standalone/tmp/vfs/temp188ec44f68d80f15/activemq-rar-5.8.0.rar-12de4b0407eb87cc/contents/
19:08:25,931 INFO [org.jboss.as.connector.deployment] (MSC service thread 1-5) JBAS010406: Registered connection factory java:jboss/ConnectionFactory
19:08:25,937 WARN [org.jboss.as.connector.deployers.RaXmlDeployer] (MSC service thread 1-5) IJ020016: Missing <recovery> element. XA recovery disabled for: java:jboss/ConnectionFactory
19:08:25,940 INFO [org.jboss.as.connector.deployment] (MSC service thread 1-5) JBAS010405: Registered admin object at java:jboss/queue/MyActiveMQQueue
19:08:25,945 INFO [org.jboss.as.connector.deployers.RaXmlDeployer] (MSC service thread 1-5) IJ020002: Deployed: file:/opt/jboss-eap-6.1/standalone/tmp/vfs/temp188ec44f68d80f15/activemq-rar-5.8.0.rar-12de4b0407eb87cc/contents/
19:08:25,950 INFO [org.jboss.as.connector.deployment] (MSC service thread 1-1) JBAS010401: Bound JCA ConnectionFactory [java:jboss/ConnectionFactory]
19:08:25,951 INFO [org.jboss.as.connector.deployment] (MSC service thread 1-6) JBAS010401: Bound JCA AdminObject [java:jboss/queue/MyActiveMQQueue]
19:08:26,118 INFO [org.jboss.as.server] (DeploymentScanner-threads – 2) JBAS018559: Deployed “activemq-rar-5.8.0.rar” (runtime-name : “activemq-rar-5.8.0.rar”)

Producer exemplo

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

/**
*
* @author sfantin
*
*/
public class Producer {

public void produce() throws JMSException, NamingException {
try {
// Obtain a JNDI connection
InitialContext jndi = new InitialContext();

// Look up a JMS connection factory
ConnectionFactory conFactory = (ConnectionFactory) jndi.lookup(“java:jboss/ConnectionFactory”);

// Getting JMS connection from the server and starting it
Connection connection = conFactory.createConnection();
connection.start();

// JMS messages are sent and received using a Session. We will
// create here a non-transactional session object. If you want
// to use transactions you should set the first parameter to ‘true’
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

Destination destination = (Destination) jndi.lookup(“java:jboss/queue/MyActiveMQQueue”);

// MessageProducer is used for sending messages (as opposed
// to MessageConsumer which is used for receiving them)
MessageProducer producer = session.createProducer(destination);

for (int i = 0; i < 1000; i++) {
producer.send(session.createTextMessage(i + ” message”));
System.out.println(“Sent message ” + i);
}
producer.close(); session.close(); connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

Obs: Assim que o primeiro produtor enviar uma mensagem para a fila MyActiveMQQueue, o message store jboss-eap-6.1/bin/activemq-data/localhost/KahaDB será criado.

MDB exemplo

import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.jms.Message;
import javax.jms.MessageListener;

import org.apache.log4j.Logger;
import org.jboss.ejb3.annotation.ResourceAdapter;

/**
*
* @author sfantin
*
*/
@MessageDriven( activationConfig = {
@ActivationConfigProperty(propertyName=”destinationType”, propertyValue=”javax.jms.Queue”),
@ActivationConfigProperty(propertyName=”destination”, propertyValue=”MyActiveMQQueue”),
@ActivationConfigProperty(propertyName=”acknowledgeMode”, propertyValue=”Auto-acknowledge”)
})
@ResourceAdapter(value=”activemq-rar-5.8.0.rar”)
public class SampleMDB implements MessageListener {

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

/*
* (non-Javadoc)
* @see javax.jms.MessageListener#onMessage(javax.jms.Message)
*/
@Override
public void onMessage(final Message msg) {
LOG.log(null, msg);

System.out.println(“received message: %s” + msg);

}

}

Download do JBoss EAP 6.1 configurado

Disponibilizei o JBoss EAP com todas as configurações comentadas neste tutorial.

JBossEAP6.1.zip

Obs: o activemq-rar-5.8.0.rar pode ser encontrado dentro do diretório /jboss-eap-6.1/standalone/deployments/

Até o próximo post!


Um Comentário on “Broker A-MQ embedded (Resource Adapter) no JBoss EAP”


Deixe uma resposta

Preencha os seus dados abaixo ou clique em um ícone para log in:

Logotipo do WordPress.com

Você está comentando utilizando sua conta WordPress.com. Sair / Alterar )

Imagem do Twitter

Você está comentando utilizando sua conta Twitter. Sair / Alterar )

Foto do Facebook

Você está comentando utilizando sua conta Facebook. Sair / Alterar )

Foto do Google+

Você está comentando utilizando sua conta Google+. Sair / Alterar )

Conectando a %s

Seguir

Obtenha todo post novo entregue na sua caixa de entrada.