integração ActiveMQ da Primavera

prefácio

Nós falar na frente de produtores e consumidores, quando a codificação são relativamente básicos, tempo e esforço para desenvolvê-los, vamos introduzir o futuro como integrar a mola para o desenvolvimento simplificar;

Configuração de consolidação

pom aumento da dependência:

 <!-- activemq连接池 -->
 <dependency>
     <groupId>org.apache.activemq</groupId>
     <artifactId>activemq-pool</artifactId>
     <version>5.15.10</version>
 </dependency>
 <!-- spring支持jms的包 -->
 <dependency>
     <groupId>org.springframework</groupId>
     <artifactId>spring-jms</artifactId>
     <version>5.2.1.RELEASE</version>
 </dependency>
 <!--spring相关依赖包-->
 <dependency>
     <groupId>org.apache.xbean</groupId>
     <artifactId>xbean-spring</artifactId>
     <version>4.15</version>
 </dependency>
 <dependency>
     <groupId>org.springframework</groupId>
     <artifactId>spring-aop</artifactId>
     <version>5.1.5.RELEASE</version>
 </dependency>
 <!-- Spring核心依赖 -->
 <dependency>
     <groupId>org.springframework</groupId>
     <artifactId>spring-core</artifactId>
     <version>4.3.23.RELEASE</version>
 </dependency>
 <dependency>
     <groupId>org.springframework</groupId>
     <artifactId>spring-context</artifactId>
     <version>4.3.23.RELEASE</version>
 </dependency>
 <dependency>
     <groupId>org.springframework</groupId>
     <artifactId>spring-aop</artifactId>
     <version>4.3.23.RELEASE</version>
 </dependency>
 <dependency>
     <groupId>org.springframework</groupId>
     <artifactId>spring-orm</artifactId>
     <version>4.3.23.RELEASE</version>
 </dependency>

Nova Primavera arquivo de configuração activeMQ integração:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

     <!--配置包自动扫描 -->
    <context:component-scan base-package="com.chaytech.activemq"/>

    <!--配置connection-->
    <bean id="connectionFactory" class="org.apache.activemq.pool.PooledConnectionFactory" destroy-method="stop">
        <property name="connectionFactory">
            <!--正真可以生产Connection的ConnectionFactory,由对应的JMS服务商提供-->
            <bean class="org.apache.activemq.spring.ActiveMQConnectionFactory">
                <!--配置activeMQ服务地址-->
                <property name="brokerURL" value="tcp://192.168.0.166:61616"/>
            </bean>
        </property>

        <!--最大连接数-->
        <property name="maxConnections" value="100"/>
    </bean>

    <!--  这个是队列目的地,点对点的Queue  -->
    <bean id="destinationQueue" class="org.apache.activemq.command.ActiveMQQueue">
        <!--    通过构造注入Queue名    -->
        <constructor-arg index="0" value="spring-active-queue"/>
    </bean>

    <!--  这个是队列目的地,  发布订阅的主题Topic-->
    <bean id="destinationTopic" class="org.apache.activemq.command.ActiveMQTopic">
        <constructor-arg index="0" value="spring-active-topic"/>
    </bean>

    <!--  Spring提供的JMS工具类,他可以进行消息发送,接收等  -->
    <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
        <!--    传入连接工厂    -->
        <property name="connectionFactory" ref="connectionFactory"/>
        <!--    传入目的地    -->
        <property name="defaultDestination" ref="destinationQueue"/>
        <!--    消息自动转换器    -->
        <property name="messageConverter">
            <bean class="org.springframework.jms.support.converter.SimpleMessageConverter"/>
        </property>
    </bean>
</beans>

produtores e consumidores de fila

package com.chaytech.activemq.spring;

import org.apache.xbean.spring.context.ClassPathXmlApplicationContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Service;

/**
 * activeMQ整合spring-生产者
 *
 * @author Chency
 * @email [email protected]
 * @Date 2020/03/24 21:41
 */
@Service
public class SpringJmsProducer {

    @Autowired
    private JmsTemplate jmsTemplate;

    public static void main(String[] args) {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-activemq.xml");

        SpringJmsProducer springJmsProducer = (SpringJmsProducer)applicationContext.getBean("springJmsProducer");
        springJmsProducer.jmsTemplate.send((session) -> {
            return session.createTextMessage("spring整合activeMQ。。");
        });
    }
}
package com.chaytech.activemq.spring;

import org.apache.xbean.spring.context.ClassPathXmlApplicationContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Service;

/**
 * activeMQ整合spring-消费者
 *
 * @author Chency
 * @email [email protected]
 * @Date 2020/03/24 21:41
 */
@Service
public class SpringJmsConsumer {

    @Autowired
    private JmsTemplate jmsTemplate;

    public static void main(String[] args) {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-activemq.xml");

        SpringJmsConsumer springJmsConsumer = (SpringJmsConsumer)applicationContext.getBean("springJmsConsumer");

        String message = (String) springJmsConsumer.jmsTemplate.receiveAndConvert();
        System.out.println("spring整合activeMQ消费者:" + message);
    }
}

produtores e consumidores Tema

produtores e consumidores Tema sem alterar o código, basta modificar os arquivos de configuração, as seguintes alterações:

 <!--  这个是队列目的地,  发布订阅的主题Topic-->
<bean id="destinationTopic" class="org.apache.activemq.command.ActiveMQTopic">
    <constructor-arg index="0" value="spring-active-topic"/>
</bean>

<!--  Spring提供的JMS工具类,他可以进行消息发送,接收等  -->
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
    <!--    传入连接工厂    -->
    <property name="connectionFactory" ref="connectionFactory"/>
    <!--    传入目的地    -->
    <!--<property name="defaultDestination" ref="destinationQueue"/>-->
    <property name="defaultDestination" ref="destinationTopic"/>
    <!--    消息自动转换器    -->
    <property name="messageConverter">
        <bean class="org.springframework.jms.support.converter.SimpleMessageConverter"/>
    </property>
</bean>

Aumenta destino tema e ponto JMSTemplate em defaultDestination nosso novo destinationTopic

consumidores ouvintes

Frente bloqueando a nossa forma de consumir notícias quando os consumidores utilizam, o seguinte irá demonstrar como usar o caminho Listener para consumir notícias, uma vez que a configuração do ouvinte, você precisa para começar um consumidor, o produtor no momento de envio de mensagens, escuta automaticamente o consumo

Em primeiro lugar, é preciso primeiro definir um ouvinte de mensagem personalizada:

package com.chaytech.activemq.spring;

import org.springframework.stereotype.Component;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

/**
 * 自定义消息监听器
 *
 * @author Chency
 * @email [email protected]
 * @Date 2020/03/24 22:05
 */
@Component
public class CustomerMessageListener implements MessageListener {

    @Override
    public void onMessage(Message message) {
        if(message != null && message  instanceof TextMessage){
            TextMessage textMessage = (TextMessage) message;
            try {
                System.out.println("自定义消息监听器监听到的消息:" + textMessage.getText());
            } catch (JMSException e) {
                e.printStackTrace();
            }
        }
    }
}

Modificar o arquivo de configuração, adicione a configuração de ouvinte:

<!--配置消费者监听器-->
<bean id="messageListenerContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
    <property name="connectionFactory" ref="connectionFactory"/>
    <property name="destination" ref="destinationTopic"/>
    <property name="messageListener" ref="customerMessageListener"/>
</bean>
Publicado 107 artigos originais · ganhou elogios 19 · vê 20000 +

Acho que você gosta

Origin blog.csdn.net/chen_changying/article/details/105082961
Recomendado
Clasificación