ActiveMQ笔记(四)和Spring、SpringBoot整合

个人感觉下面的整合方式也不是很好,可以参照网上其他整合方式;本文可以用来参考

一 和Spring整合

主要就是看个大概流程,实际用到的时候知道如何封装

1.1 依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.rocket</groupId>
    <artifactId>test_activemq</artifactId>
    <version>1.0-SNAPSHOT</version>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.targer>1.8</maven.compiler.targer>
    </properties>
    <dependencies>
        <!--activemq需要的jav包(这个不整合也需要)-->
        <dependency>
            <groupId>org.apache.activemq</groupId>
            <artifactId>activemq-all</artifactId>
            <version>5.15.9</version>
        </dependency>
        <dependency>
            <groupId>org.apache.xbean</groupId>
            <artifactId>xbean-spring</artifactId>
            <version>3.16</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.5</version>
        </dependency>

		<!--activemq对JMS的支持,整合Spring和ActiveMQ-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jms</artifactId>
            <version>4.3.23.RELEASE</version>
        </dependency>

		<!--activemq所需要的pool-->
        <dependency>
            <groupId>org.apache.activemq</groupId>
            <artifactId>activemq-pool</artifactId>
            <version>5.15.9</version>
        </dependency>

        <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>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.6.1</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.6.8</version>
        </dependency>
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>2.1_2</version>
        </dependency>



        <!--下面是junit/log4等通用配置-->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.25</version>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.3</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.18</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>
</project>
 

1.2 Spring配置文件

<?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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx" 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/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

        <context:component-scan base-package="com.atguigu.activemq"></context:component-scan>

		<!--配置生产者-->
        <bean id="jmsFactory" class="org.apache.activemq.pool.PooledConnectionFactory" destroy-method="stop">
        		<!--真正可以生产Connection的Factory,由对于的JMS服务厂商提供 -->
                <property name="connectionFactory">
                        <bean class="org.apache.activemq.ActiveMQConnectionFactory">
                                <property name="brokerURL" value="tcp://10.112.70.211:61616"/>
                        </bean>
                </property>
                <property name="maxConnections" value="100"></property>
        </bean>


		<!--队列的目的地,点对点 -->
        <bean id="destinationQueue" class="org.apache.activemq.command.ActiveMQQueue">
       			 <!--构造注入,参数是字符串(不是ref),表示队列名称 -->
                <constructor-arg index="0" value="spring-active-queue"/>
        </bean>

        <!-- Spring的JMS模版工具 -->
        <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
                <property name="connectionFactory" ref="jmsFactory" />
                <property name="defaultDestination" ref="destinationQueue"/>
                <property name="messageConverter">
                        <bean class="org.springframework.jms.support.converter.SimpleMessageConverter" />
                </property>
        </bean>

</beans>
 

1.3 基于队列

生产者

package com.atguigu.activemq.spring;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;

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

/**
 * @ClassName SpringMQ_Consumer
 * @Description TODO
 * @Author DuanYueFeng
 * @Version 1.0
 **/
@Service
public class SpringMQ_Producer {
    @Autowired
    private JmsTemplate jmsTemplate;

    public static void main(String[] args) {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");	
		//自己获取自己
        SpringMQ_Producer producer = (SpringMQ_Producer) applicationContext.getBean("springMQ_Producer");

        producer.jmsTemplate.send(new MessageCreator() {
            @Override
            public Message createMessage(Session session) throws JMSException {

                TextMessage textMessage = session.createTextMessage("Spring+Active。。。。");
                return textMessage;
            }
        });
        
    }
}
 
 

消费者

package com.atguigu.activemq.spring;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;

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

/**
 * @ClassName SpringMQ_Consumer
 * @Description TODO
 * @Author DuanYueFeng
 * @Version 1.0
 **/
@Service
public class SpringMQ_Consumer {

    @Autowired
    private JmsTemplate jmsTemplate;

    public static void main(String[] args) throws JMSException {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        SpringMQ_Consumer consumer = (SpringMQ_Consumer) applicationContext.getBean("springMQ_Consumer");
//        TextMessage receive =(TextMessage) consumer.jmsTemplate.receive();
        String receive =(String) consumer.jmsTemplate.receiveAndConvert();
        System.out.println("消费者:"+receive);
    }
}
 
 

1.4 基于主题

新增一个主题

<?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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx" 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/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

        <context:component-scan base-package="com.atguigu.activemq"></context:component-scan>

        <bean id="jmsFactory" class="org.apache.activemq.pool.PooledConnectionFactory" destroy-method="stop">
                <property name="connectionFactory">
                        <bean class="org.apache.activemq.ActiveMQConnectionFactory">
                                <property name="brokerURL" value="tcp://10.112.70.211:61616"/>
                        </bean>
                </property>
                <property name="maxConnections" value="100"></property>
        </bean>


		<!-- 这里变成主题 -->
        <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="jmsFactory" />
                <property name="defaultDestination" ref="destinationTopic"/>
                <property name="messageConverter">
                        <bean class="org.springframework.jms.support.converter.SimpleMessageConverter" />
                </property>
        </bean>

</beans>
 

生产者

同队列代码不变

消费者

同队列代码不变

1.5 配置消费者监听器

前面的消费者类似API的receive方法来接收消息

配置文件

<?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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx" 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/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

        <context:component-scan base-package="com.atguigu.activemq"></context:component-scan>

        <bean id="jmsFactory" class="org.apache.activemq.pool.PooledConnectionFactory" destroy-method="stop">
                <property name="connectionFactory">
                        <bean class="org.apache.activemq.ActiveMQConnectionFactory">
                                <property name="brokerURL" value="tcp://10.112.70.211:61616"/>
                        </bean>
                </property>
                <property name="maxConnections" value="100"></property>
        </bean>

        <bean id="destinationQueue" class="org.apache.activemq.command.ActiveMQQueue">
                <constructor-arg index="0" value="spring-active-queue"/>
        </bean>
        <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="jmsFactory" />
                <property name="defaultDestination" ref="destinationTopic"/>
                <property name="messageConverter">
                        <bean class="org.springframework.jms.support.converter.SimpleMessageConverter" />
                </property>
        </bean>

        <bean id="queueListenerContainer"
              class="org.springframework.jms.listener.DefaultMessageListenerContainer">
                <property name="connectionFactory" ref="jmsFactory" />
                <property name="destination" ref="destinationTopic" />
                <property name="messageListener" ref="myMessageListener" />
        </bean>


</beans>
 

监听器类

package com.atguigu.activemq.spring;

import org.springframework.stereotype.Service;

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

/**
 * @ClassName MyMessageListener
 * @Description TODO
 * @Author DuanYueFeng
 * @Version 1.0
 **/
@Service
public class MyMessageListener implements MessageListener {
    @Override
    public void onMessage(Message message) {
        if (null != message && message instanceof TextMessage){
            TextMessage textMessage = (TextMessage) message;
            try {
                System.out.println("spring消费者接收到消息:"+textMessage.getText());
            } catch (JMSException e) {
                e.printStackTrace();
            }
        }
    }
}
 
 

二 和Springboot整合-队列

2.1 依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.5.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.rocket</groupId>
    <artifactId>springboot_activemq</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot_activemq</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.targer>1.8</maven.compiler.targer>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-activemq</artifactId>
            <version>2.1.5.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>



</project>
 
 

2.2 yml配置

server:
  port: 7777
spring:
  activemq:
    broker-url: tcp://10.112.70.211:61616
    user: admin
    password: admin
  jms:
    pub-sub-domain: false # false=Queue,true=Topic
#自定义队列名称
myqueue: boot-activemq-queue

2.3 配置类

package com.rocket.springboot_activemq.config;

import org.apache.activemq.command.ActiveMQQueue;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import javax.jms.Queue;


@Component
@EnableJms
public class ConfigBean {

  	@Value("${myqueue}")
    private String myQueue;

    @Bean
    public Queue queue(){
        return new ActiveMQQueue(myQueue);
    }
}
 


2.4 生产者

package com.rocket.springboot_activemq.produce;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.stereotype.Component;

import javax.jms.Queue;
import java.util.UUID;


@Component
public class Queue_Produce {
    @Autowired
    private JmsMessagingTemplate jmsMessagingTemplate;
    @Autowired
    private Queue queue;

    public void produceMsg(){
        jmsMessagingTemplate.convertAndSend(queue,"******:"+ UUID.randomUUID().toString().substring(0,6));
    }
}
 
 

2.5 消费者

package com.rocket.boot_mq_consumer.consumer;

import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Service;

import javax.jms.JMSException;
import javax.jms.TextMessage;


@Service
public class QueueConsumer {

    @JmsListener(destination = "${myqueue}")
    public void receive(TextMessage textMessage) throws JMSException {
        System.out.println("消费者接受消息:"+textMessage.getText());
    }
}

三 和Springboot整合-主题

3.1 yml配置

server:
  port: 7777
spring:
  activemq:
    broker-url: tcp://10.112.70.211:61616
    user: admin
    password: admin
  jms:
    pub-sub-domain: true

mytopic: boot-activemq-topic
 
 

3.2 生产者

package com.rocket.boot_mq_topic.produce;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.jms.Queue;
import javax.jms.Topic;
import java.util.UUID;


@Component
public class Topic_Produce {
    @Autowired
    private JmsMessagingTemplate jmsMessagingTemplate;
    @Autowired
    private Topic topic;

    public void produceMsg(){
        jmsMessagingTemplate.convertAndSend(topic,"Topic******:"+ UUID.randomUUID().toString().substring(0,6));
    }
    @Scheduled(fixedDelay = 3000)
    public void produceMsgScheduled(){
        jmsMessagingTemplate.convertAndSend(topic,"Topic******Scheduled:"+ UUID.randomUUID().toString().substring(0,6));
        System.out.println("发送消息。。。");
    }
}
 
 

3.3 消费者

package com.rocket.boot_mq_topic_consumer.consumer;

import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Service;

import javax.jms.JMSException;
import javax.jms.TextMessage;


@Service
public class TopicConsumer {

    @JmsListener(destination = "${myqueue}")
    public void receive(TextMessage textMessage) throws JMSException {
        System.out.println("消费者接受消息:"+textMessage.getText());
    }
}
 
 

四 整合参考

发布了82 篇原创文章 · 获赞 1 · 访问量 1952

猜你喜欢

转载自blog.csdn.net/m0_38060977/article/details/103753498
今日推荐