1.创建Maven项目,在pom.xml中导入相应jar包
<?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/> </parent> <groupId>org.example</groupId> <artifactId>activemq_springboot_demo</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.target>1.8</maven.compiler.target> </properties> <dependencies> <!--spring-boot--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <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-test</artifactId> </dependency> <!--activemq--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-activemq</artifactId> <version>2.1.5.RELEASE</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
2.在resources目录下创建application.yml
server:
port: 8888
spring:
activemq:
broker-url: tcp://192.168.231.128:61616 #自己的MQ地址
user: admin
password: admin
jms:
pub-sub-domain:true #默认是:false = 队列(Queue) true = Topic
#定义自己的队列名称
myTopic: boot-activemq-Topic
3.创建主程序启动类
/** * @author 主启动类 */ @SpringBootApplication @EnableScheduling //开启定时任务 public class MainApp_Produce { public static void main(String[] args) { SpringApplication.run(MainApp_Produce.class,args); } }
4.创建配置类读取application.yml文件中的Topic
/** * @author 读取配置的Topic */ @Component @EnableJms //开启Jms public class ConfigBean { @Value("${myTopic}") private String myTopic; @Bean //<bean id="" class=""/> public Topic topic() { return new ActiveMQTopic(myTopic); } }
5.创建队列的生产者
@Component public class Topic_Produce { @Autowired private JmsMessagingTemplate jmsMessagingTemplate; @Autowired private Topic topic; @Scheduled(fixedDelay = 3000) public void produceTopic() { jmsMessagingTemplate.convertAndSend(topic,"主题消息"+ UUID.randomUUID().toString().substring(0,6)); } }
6.创建队列的消费者
@Component public class Topic_Consumer { @JmsListener(destination = "${myTopic}") //开启自动监听 public void receive(TextMessage textMessage) throws JMSException { System.out.println("消费者收到订阅的主题"+ textMessage.getText()); } }