六、Spring/Spring Boot整合ActiveMQ

news2025/3/14 1:09:24

Spring/Spring Boot整合ActiveMQ

  • 一、Spring整合ActiveMQ
    • 1.pom.xml
    • 2.Queue - 队列
      • 2.1 applicationContext.xml
      • 2.2 生产者
      • 2.3 消费者
    • 3.Topic - 主题
      • 3.1 applicationContext.xml
      • 3.2 生产者
      • 3.3 消费者
    • 4.消费者 - 监听器
      • 4.1 编写监听器类
      • 4.2 配置监听器
      • 4.3 生产者+消费者一体
  • 二、Spring Boot整合ActiveMQ
    • 1.Queue - 队列
      • 1.1 生产者
        • 1.1.1 创建Maven工程
        • 1.1.2 pom.xml
        • 1.1.3 application.yml
        • 1.1.4 创建配置文件Bean
        • 1.1.5 生产者
        • 1.1.6 主启动类
        • 1.1.7 测试单元类
        • 1.1.8 案例-定时投递
      • 1.2 消费者
        • 1.2.1 创建Maven工程
        • 1.2.2 pom.xml
        • 1.2.3 application.yml
        • 1.2.4 消费者-监听类
        • 1.2.5 主启动类
    • 2.Topic - 主题
      • 2.1 生产者
        • 2.1.1 创建Maven工程
        • 2.1.2 pom.xml
        • 2.1.3 application.yml
        • 2.1.4 创建配置文件Bean
        • 2.1.5 生产者
        • 2.1.6 主启动类
      • 2.2 消费者
        • 2.2.1 创建Maven工程
        • 2.2.2 pom.xml
        • 2.2.3 application.yml
        • 2.2.4 消费者
        • 2.2.5 主启动类

一、Spring整合ActiveMQ

1.pom.xml

<?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.qingsi.activemq</groupId>
    <artifactId>activemq_test</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <!-- activemq所需要的jar包配置 -->
            <groupId>org.apache.activemq</groupId>
            <artifactId>activemq-all</artifactId>
            <version>5.15.11</version>
        </dependency>
        <!-- 池化技术 -->
        <dependency>
            <groupId>org.apache.activemq</groupId>
            <artifactId>activemq-pool</artifactId>
            <version>5.15.10</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.10.1</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.apache.xbean/xbean-spring -->
        <dependency>
            <groupId>org.apache.xbean</groupId>
            <artifactId>xbean-spring</artifactId>
            <version>4.15</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework/spring-jms -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jms</artifactId>
            <version>5.2.1.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-aop -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>5.2.1.RELEASE</version>
        </dependency>

        <!--  下面是junit/logback等基础配置  -->
        <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>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>

</project>

2.Queue - 队列

2.1 applicationContext.xml

  • 路径:src/main/resources/applicationContext.xml
<?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 https://www.springframework.org/schema/context/spring-context.xsd">

    <!--  开启包的自动扫描  -->
    <context:component-scan base-package="com.qingsi.activemq"/>
    <!--  配置生产者  -->
    <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">
                <property name="brokerURL" value="tcp://192.168.86.128: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>

    <!--  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>

2.2 生产者

package com.qingsi.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.jms.core.MessageCreator;
import org.springframework.stereotype.Service;

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

@Service
public class SpringMQProduce {
    @Autowired
    private JmsTemplate jmsTemplate;

    public static void main(String[] args) {
        // 获取配置文件对象
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        // 获取SpringMQProduce对象,用于调用jmsTemplate
        // 下面等同于 new SpringMQProduce(),但是交给Spring管理,他只会new一次,后续都是用同一个实例对象
        SpringMQProduce produce = ctx.getBean(SpringMQProduce.class);

        // 由于 目标队列 在配置文件指定了,所以在发送的时候不需要再指定
        produce.jmsTemplate.send(new MessageCreator() {
            @Override
            public Message createMessage(Session session) throws JMSException {
                TextMessage textMessage = session.createTextMessage("Spring和Active整合的消息");
                return textMessage;
            }
        });
        // 下面是lambda表达式写法,和上面效果一样
        // produce.jmsTemplate.send((session -> {
        //     TextMessage textMessage = session.createTextMessage("Spring和Active整合的消息");
        //     return textMessage;
        // }));

        System.out.println("消息发送完毕");

    }

}

2.3 消费者

package com.qingsi.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;

@Service
public class SpringMQConsumer {

    @Autowired
    private JmsTemplate jmsTemplate;

    public static void main(String[] args) {
        // 获取配置文件对象
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        // 获取SpringMQConsumer对象,用于调用jmsTemplate
        // 下面等同于 new SpringMQConsumer(),但是交给Spring管理,他只会new一次,后续都是用同一个实例对象
        SpringMQConsumer consumer = ctx.getBean(SpringMQConsumer.class);

        String retValue = (String) consumer.jmsTemplate.receiveAndConvert();

        System.out.println("spring消费者收到的消息:" + retValue);
    }

}

3.Topic - 主题

3.1 applicationContext.xml

  • 路径:src/main/resources/applicationContext.xml
<?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 https://www.springframework.org/schema/context/spring-context.xsd">

    <!--  开启包的自动扫描  -->
    <context:component-scan base-package="com.qingsi.activemq"/>
    <!--  配置生产者  -->
    <bean id="connectionFactory" class="org.apache.activemq.pool.PooledConnectionFactory" destroy-method="stop">
        <property name="connectionFactory">
            <!--      正真可以生产ConnectionConnectionFactory,由对应的JMS服务商提供  -->
            <bean class="org.apache.activemq.spring.ActiveMQConnectionFactory">
                <property name="brokerURL" value="tcp://192.168.86.128:61616"/>
            </bean>
        </property>
        <property name="maxConnections" value="100"/>
    </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="destinationTopic"/>
        <!--    消息自动转换器    -->
        <property name="messageConverter">
            <bean class="org.springframework.jms.support.converter.SimpleMessageConverter"/>
        </property>
    </bean>
</beans>

3.2 生产者

  • 和队列的代码一样,只是在配置文件里面改了destination

3.3 消费者

  • 和队列的代码一样,只是在配置文件里面改了destination

4.消费者 - 监听器

  • 实现目标:在Spring里面实现消费者不启动,直接通过配置监听完成
  • 类似于前面setMessageListenner实时间提供消息
  • 注意:配置了监听器,那么启动生产者,就会自动消费,不需要再启动消费者了

4.1 编写监听器类

package com.qingsi.activemq.spring;

import org.springframework.stereotype.Component;

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

@Component
public class MyMessageListener implements MessageListener {
    @Override
    public void onMessage(Message message) {
        if (message instanceof TextMessage){
            TextMessage textMessage = (TextMessage) message;
            try {
                System.out.println("收到消息: " + textMessage.getText());
            } catch (JMSException e) {
                e.printStackTrace();
            }
        }
    }
}

4.2 配置监听器

  • applicationContext.xml
<?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 https://www.springframework.org/schema/context/spring-context.xsd">

    <!--  开启包的自动扫描  -->
    <context:component-scan base-package="com.qingsi.activemq"/>
    <!--  配置生产者  -->
    <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">
                <property name="brokerURL" value="tcp://192.168.86.128:61616"/>
            </bean>
        </property>
        <property name="maxConnections" value="100"/>
    </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="destinationTopic"/>
        <!--    消息自动转换器    -->
        <property name="messageConverter">
            <bean class="org.springframework.jms.support.converter.SimpleMessageConverter"/>
        </property>
    </bean>

    <!--  配置Jms消息监听器  -->
    <bean id="defaultMessageListenerContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
        <!--  Jms连接的工厂     -->
        <property name="connectionFactory" ref="connectionFactory"/>
        <!--   设置默认的监听目的地     -->
        <property name="destination" ref="destinationTopic"/>
        <!--  指定自己实现了MessageListener的类     -->
        <property name="messageListener" ref="myMessageListener"/>
    </bean>
</beans>

4.3 生产者+消费者一体

package com.qingsi.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.jms.core.MessageCreator;
import org.springframework.stereotype.Service;

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

@Service
public class SpringMQProduce {
    @Autowired
    private JmsTemplate jmsTemplate;

    public static void main(String[] args) {
        // 获取配置文件对象
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        // 获取SpringMQProduce对象,用于调用jmsTemplate
        // 下面等同于 new SpringMQProduce(),但是交给Spring管理,他只会new一次,后续都是用同一个实例对象
        SpringMQProduce produce = ctx.getBean(SpringMQProduce.class);

        // 由于 目标队列 在配置文件指定了,所以在发送的时候不需要再指定
         produce.jmsTemplate.send((session -> {
             TextMessage textMessage = session.createTextMessage("Spring和Active整合的消息");
             return textMessage;
         }));

        System.out.println("消息发送完毕");

    }

}

二、Spring Boot整合ActiveMQ

1.Queue - 队列

1.1 生产者

1.1.1 创建Maven工程
  • 这里有案例,根据实际来创建:https://qingsi.blog.csdn.net/article/details/136130132
  • 我创建了
    • 工程名:boot_activemq_test
    • 包名:com.qingsi.boot.activemq
      在这里插入图片描述
1.1.2 pom.xml
<?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.qingsi.boot.activemq</groupId>
    <artifactId>boot_activemq_test</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
            <version>2.2.1.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.2.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <version>2.2.1.RELEASE</version>
            <scope>test</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-activemq</artifactId>
            <version>2.2.1.RELEASE</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.2.1.RELEASE</version>
            </plugin>
        </plugins>
    </build>

</project>
1.1.3 application.yml
  • 路径:src/main/resources/application.yml
#Springboot启动端口
server:
  port: 8080

#ActiveMQ配置
spring:
  activemq:
    broker-url: tcp://192.168.86.128:61616 #ActiveMQ服务器IP
    user: admin #ActiveMQ连接用户名
    password: admin #ActiveMQ连接密码
  jms:
    #指定连接队列还是主题
    pub-sub-domain: false # false = Queue |  true = Topic

#定义服务上的队列名
myqueue: springboot-activemq-queue
1.1.4 创建配置文件Bean
package com.qingsi.boot.activemq.config;

import javax.jms.Queue;

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

@Component
@EnableJms
public class ConfigBean {
    // 从配置文件读取 队列名称
    @Value("${myqueue}")
    private String myQueue;

    // 通过 队列名称 创建队列
    @Bean
    public Queue queue() {
        return new ActiveMQQueue(myQueue);
    }
}
1.1.5 生产者
package com.qingsi.boot.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 QueueProduce {

    @Autowired
    private JmsMessagingTemplate jmsMessagingTemplate;

    @Autowired
    private Queue queue;

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

1.1.6 主启动类
package com.qingsi.boot.activemq;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class MainAppProduce {
    public static void main(String[] args) {
        SpringApplication.run(MainAppProduce.class, args);
    }
}

1.1.7 测试单元类
package com.qingsi.boot.activemq;

import com.qingsi.boot.activemq.produce.QueueProduce;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;

import javax.annotation.Resource;

@SpringBootTest(classes = MainAppProduce.class)
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
public class TestActiveMQ {
    @Resource
    private QueueProduce queueProduce;

    @Test
    public void testSend() {
        queueProduce.produceMsg();
    }
}
  • 运行测试类
    在这里插入图片描述
1.1.8 案例-定时投递
  • 要求每隔3秒钟,往MQ推送消息

生产者

package com.qingsi.boot.activemq.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 java.util.UUID;

@Component
public class QueueProduce {

    @Autowired
    private JmsMessagingTemplate jmsMessagingTemplate;

    @Autowired
    private Queue queue;

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

    // 间隔实际3秒定投
    @Scheduled(fixedDelay = 3000)
    public void produceMsgScheduled(){
        jmsMessagingTemplate.convertAndSend(queue, "-----" + UUID.randomUUID().toString().substring(0, 6));
    }
}

主启动类

  • 开启Schedule
package com.qingsi.boot.activemq;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling
public class MainAppProduce {
    public static void main(String[] args) {
        SpringApplication.run(MainAppProduce.class, args);
    }
}

  • 启动主启动类,就会定时发消息了

1.2 消费者

1.2.1 创建Maven工程
  • 这里有案例,根据实际来创建:https://qingsi.blog.csdn.net/article/details/136130132
  • 我创建了
    • 工程名:boot_activemq_consumer
    • 包名:com.qingsi.boot.activemq
      在这里插入图片描述
1.2.2 pom.xml
<?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.qingsi.boot.activemq</groupId>
    <artifactId>boot_activemq_consumer</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
            <version>2.2.1.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.2.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <version>2.2.1.RELEASE</version>
            <scope>test</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-activemq</artifactId>
            <version>2.2.1.RELEASE</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.2.1.RELEASE</version>
            </plugin>
        </plugins>
    </build>
</project>
1.2.3 application.yml
#Springboot启动端口
server:
  port: 8888

#ActiveMQ配置
spring:
  activemq:
    broker-url: tcp://192.168.86.128:61616 #ActiveMQ服务器IP
    user: admin #ActiveMQ连接用户名
    password: admin #ActiveMQ连接密码
  jms:
    #指定连接队列还是主题
    pub-sub-domain: false # false = Queue |  true = Topic

#定义服务上的队列名
myqueue: springboot-activemq-queue

1.2.4 消费者-监听类
package com.qingsi.activemq.consumer;


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

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

@Component
public class QueueConsumer {

    // 开启监听
    @JmsListener(destination = "${myqueue}")
    public void receive(TextMessage textMessage) throws JMSException {
        System.out.println("消费者收到消息:" + textMessage.getText());
    }
}
1.2.5 主启动类
  • 开启Jms监听
package com.qingsi.activemq;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class MainAppConsumer {
    public static void main(String[] args) {
        SpringApplication.run(MainAppConsumer.class, args);
    }
}

2.Topic - 主题

2.1 生产者

2.1.1 创建Maven工程
  • 这里有案例,根据实际来创建:https://qingsi.blog.csdn.net/article/details/136130132
  • 我创建了
    • 工程名:boot_mq_topic_produce
    • 包名:com.qingsi.boot.activemq.topic.produce
2.1.2 pom.xml
<?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.qingsi.boot.activemq.topic.produce</groupId>
    <artifactId>boot_mq_topic_produce</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
            <version>2.2.1.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.2.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <version>2.2.1.RELEASE</version>
            <scope>test</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-activemq</artifactId>
            <version>2.2.1.RELEASE</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.2.1.RELEASE</version>
            </plugin>
        </plugins>
    </build>

</project>
2.1.3 application.yml
#Springboot启动端口
server:
  port: 6666

#ActiveMQ配置
spring:
  activemq:
    broker-url: tcp://192.168.86.128:61616 #ActiveMQ服务器IP
    user: admin #ActiveMQ连接用户名
    password: admin #ActiveMQ连接密码
  jms:
    #指定连接队列还是主题
    pub-sub-domain: true # false = Queue |  true = Topic

#定义服务上的队列名
myTopic: springboot-activemq-topic
2.1.4 创建配置文件Bean
package com.qingsi.boot.activemq.topic.config;

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

import javax.jms.Topic;

@Component
public class ConfigBean {

    @Value("${myTopic}")
    private String topicName;

    @Bean
    public Topic topic(){
        return new ActiveMQTopic(topicName);
    }

}

2.1.5 生产者
package com.qingsi.boot.activemq.topic.com.qingsi.boot.activemq.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.Topic;
import java.util.UUID;

@Component
public class TopicProduce {
    @Autowired
    private JmsMessagingTemplate jmsMessagingTemplate;

    @Autowired
    private Topic topic;

    // 间隔实际3秒定投
    @Scheduled(fixedDelay = 3000)
    public void produceTopic() {
        jmsMessagingTemplate.convertAndSend(topic, "主题消息: " + UUID.randomUUID().toString().substring(0, 6));
    }

}

2.1.6 主启动类
package com.qingsi.boot.activemq.topic;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling
public class MainAppTopicProduce {
    public static void main(String[] args) {
        SpringApplication.run(MainAppTopicProduce.class, args);
    }

}

2.2 消费者

2.2.1 创建Maven工程
  • 这里有案例,根据实际来创建:https://qingsi.blog.csdn.net/article/details/136130132
  • 我创建了
    • 工程名:boot_mq_topic_consumer
    • 包名:com.qingsi.boot.activemq.topic.consumer
2.2.2 pom.xml
<?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.qingsi.boot.activemq.topic.consumer</groupId>
    <artifactId>boot_mq_topic_consumer</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
            <version>2.2.1.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.2.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <version>2.2.1.RELEASE</version>
            <scope>test</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-activemq</artifactId>
            <version>2.2.1.RELEASE</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.2.1.RELEASE</version>
            </plugin>
        </plugins>
    </build>

</project>
2.2.3 application.yml
#Springboot启动端口
server:
  port: 5555

#ActiveMQ配置
spring:
  activemq:
    broker-url: tcp://192.168.86.128:61616 #ActiveMQ服务器IP
    user: admin #ActiveMQ连接用户名
    password: admin #ActiveMQ连接密码
  jms:
    #指定连接队列还是主题
    pub-sub-domain: true # false = Queue |  true = Topic

#定义服务上的队列名
myTopic: springboot-activemq-topic
2.2.4 消费者
package com.qingsi.activemq.topic.consumer;

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

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

@Component
public class TopicConsumer {
    // 开启监听
    @JmsListener(destination = "${myTopic}")
    public void receive(TextMessage textMessage) throws JMSException {
        System.out.println("消费者收到消息:" + textMessage.getText());
    }
}

2.2.5 主启动类
package com.qingsi.activemq.topic;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class MainAppTopicConsumer {
    public static void main(String[] args) {
        SpringApplication.run(MainAppTopicConsumer.class, args);
    }

}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1453563.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

基于PPNSA+扰动算子的车间调度最优化matlab仿真,可以任意调整工件数和机器数,输出甘特图

目录 1.程序功能描述 2.测试软件版本以及运行结果展示 3.核心程序 4.本算法原理 5.完整程序 1.程序功能描述 基于PPNSA扰动算子的车间调度最优化matlab仿真,可以任意调整工件数和机器数,输出甘特图和优化收敛曲线。 2.测试软件版本以及运行结果展示 MATLAB2022a版本运行…

Java毕业设计-基于ssm的网上餐厅管理系统-第72期

获取源码资料&#xff0c;请移步从戎源码网&#xff1a;从戎源码网_专业的计算机毕业设计网站 项目介绍 基于ssm的网上餐厅管理系统&#xff1a;前端jsp、jquery、bootstrap&#xff0c;后端 maven、springmvc、spring、mybatis&#xff0c;集成类名管理、菜品管理、订单管理…

Linux第59步_“buildroot”构建根文件系统第1步_生成rootfs.tar和rootfs.ext4以及通过nfs下载测试

学习安装“buildroot”&#xff0c;通过配置构建根文件系统&#xff0c;编译生成rootfs.tar和rootfs.ext4&#xff0c;以及通过nfs下载测试。 1、了解学习目的&#xff1a; 1)、获取“buildroot”安装包&#xff1b; 2)、使用“buildroot”构建根文件系统&#xff1b; 3)、…

使用Apache ECharts同时绘制多个统计图表

目录 1、介绍 2、相关知识 3、代码 4、效果 &#x1f343;作者介绍&#xff1a;双非本科大三网络工程专业在读&#xff0c;阿里云专家博主&#xff0c;专注于Java领域学习&#xff0c;擅长web应用开发、数据结构和算法&#xff0c;初步涉猎Python人工智能开发和前端开发。 …

UE Get节点和源码

文章目录 概要UE Get节点有哪些常见的应用场景相关源码 概要 UE Get节点在Unreal Engine的蓝图系统中用于获取变量的值。这个节点通常用于从变量中读取数据&#xff0c;以便在游戏的逻辑流程中使用。 要使用Get节点&#xff0c;你首先需要有一个已经定义的变量。然后&#xf…

Windows环境部署nginx 文件服务器

文章目录 前言一、pandas是什么&#xff1f;二、使用步骤 1.引入库2.读入数据总结 前言 在Windows环境下使用nginx部署简单的文件服务器 一、版本 1. Windows 使用版本 2. nginx 使用版本 选择Mainline Version版本 二、nginx配置 1. 下载 https://nginx.org/en/download.…

Unity 减低GC和优化

文章目录 在Unity中&#xff0c;垃圾收集&#xff08;Garbage Collection, GC&#xff09;是一项重要的内存管理机制&#xff0c;但过度的GC活动可能会导致性能瓶颈。优化Unity项目中的GC涉及减少不必要的对象分配和生命周期管理。以下列举了五个实例来详细说明如何降低GC负担并…

用于图像处理的Python顶级库 !!

文章目录 前言 1、OpenCV 2、Scikit-Image 3、Scipy 4、Python Image Library&#xff08;Pillow / PIL&#xff09; 5、Matplotlib 6、SimpleITK 7、Numpy 8、Mahotas 前言 正如IDC所指出的&#xff0c;数字信息将飙升至175ZB&#xff0c;而这些信息中的巨大一部分是图片。数…

安卓实现简单砸地鼠游戏

效果 布局 <LinearLayout xmlns:android"http://schemas.android.com/apk/res/android"xmlns:app"http://schemas.android.com/apk/res-auto"xmlns:tools"http://schemas.android.com/tools"android:layout_width"match_parent"a…

开年炸裂-Sora/Gemini

最新人工智能消息 谷歌的新 Gemini 模型 支持多达 1M的Token&#xff0c;可以分析长达一小时的视频 1M Token可能意味着分析700,000 个单词、 30,000 行代码或11 小时的音频、总结、改写和引用内容。 Comment&#xff1a;google公司有夸大的传统&#xff0c;所以真实效果需要上…

【自然语言处理】实验3,文本情感分析

清华大学驭风计划课程链接 学堂在线 - 精品在线课程学习平台 (xuetangx.com) 代码和报告均为本人自己实现&#xff08;实验满分&#xff09;&#xff0c;只展示主要任务实验结果&#xff0c;如果需要详细的实验报告或者代码可以私聊博主 有任何疑问或者问题&#xff0c;也欢…

2024/2/17 图论 最短路入门 dijkstra 1

目录 算法思路 Dijkstra求最短路 AcWing 849. Dijkstra求最短路 I - AcWing 850. Dijkstra求最短路 II - AcWing题库 最短路 最短路 - HDU 2544 - Virtual Judge (vjudge.net) 【模板】单源最短路径&#xff08;弱化版&#xff09; P3371 【模板】单源最短路径&#xf…

文生视频提示词:故事与主题

内容创意 --故事与主题 Story & Theme 这些词汇覆盖了从基本的故事类型到特定的主题和元素&#xff0c;可用于激发创意和定义视频内容的核心主题。 Adventure 冒险 Romance 浪漫 Mystery 神秘 Fantasy 幻想 Science Fiction 科幻 Horror 恐怖 Thriller 惊悚 Comedy 喜剧 Dr…

EXCEL中不错的xlookup函数

excel中一般要经常用vlookup函数&#xff0c;但其实经常麻烦要正序&#xff0c;从左边到右边&#xff0c;还要数列&#xff0c;挺麻烦的&#xff0c;xlookup的函数还不错&#xff0c;有个不错的一套视频介绍,B站的&#xff0c;地址是&#xff1a;XLOOKUP函数基础用法&#xff0…

Python vars函数

在Python编程中&#xff0c;vars()函数是一个常用的内置函数&#xff0c;用于返回对象的__dict__属性。该属性存储了对象的命名空间&#xff0c;包括对象的所有属性和方法。本文将深入探讨Python中的vars()函数&#xff0c;包括基本用法、适用对象、返回结果、实际应用场景&…

MySQL数据库⑪_C/C++连接MySQL_发送请求

目录 1. 下载库文件 2. 使用库 3. 链接MySQL函数 4. C/C链接示例 5. 发送SQL请求 6. 获取查询结果 本篇完。 1. 下载库文件 要使用C/C连接MySQL&#xff0c;需要使用MySQL官网提供的库。 进入MySQL官网选择适合自己平台的mysql connect库&#xff0c;然后点击下载就行…

线程库接口模拟封装(使用参数包接受参数,2种方法)

目录 引入 模拟实现 思路 传递参数包 代码 thread.hpp main.cpp 示例 引入 之前我们一直使用的都是linux中的原生线程库,但c中其实是有提供封装好的线程库的 -- <thread> 下面我们也来试着封装一下线程接口 模拟实现 思路 首先,明确线程库的核心操作: 创建和销毁…

标签结构比目录结构更易用 | Obsidian实践

当我顿悟了标签结构&#xff08;标签树&#xff09;的构建逻辑&#xff0c;彻底摆脱了目录结构的限制&#xff0c;从此可按任意维度管理和检索笔记。 对于每一个新入坑Obsidian的小白菜来说&#xff0c;通过创建目录结构&#xff0c;对笔记进行管理是最符合直觉的方式。但是&am…

【AIGC】大语言模型

大型语言模型&#xff0c;也叫大语言模型、大模型&#xff08;Large Language Model&#xff0c;LLM&#xff1b;Large Language Models&#xff0c;LLMs&#xff09; 什么是大型语言模型 大型语言模型&#xff08;LLM&#xff09;是指具有数千亿&#xff08;甚至更多&#xf…

php switch、for、foreach、while、do...while

php switch 1. switch2. for循环3. foreach4. while、do...while 1. switch <?php$height 190;switch ($height) {case 160:echo 太矮了;break; //跳出本次循环case 170:echo 还行吧;break; //跳出本次循环case 180:echo 帅哥;break; //跳出本次循环default:echo 迷; }2.…