新建maven工程,我的工程名叫SpringBootActiveMQTopicProducer。
pom.xml,application.yml参考这篇博客:https://blog.csdn.net/qq_36059561/article/details/103834916
注意需要修改的一个地方,在application.yml中spring.jms.pub-sub-domain的值要设置成true,表示topic,下面的myqueue: boot-activemq-queue改成mytopic: boot-activemq-topic。
创建ConfigBean.java,编写代码,代码如下。
package com.wsy.boot.activemq.config;
import org.apache.activemq.command.ActiveMQTopic;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.jms.annotation.EnableJms;
import org.springframework.stereotype.Component;
import javax.jms.Topic;
@Component
@EnableJms// 开启JMS适配的注解
public class ConfigBean {
@Value("${mytopic}")
private String myTopic;
@Bean
public Topic topic() {
return new ActiveMQTopic(myTopic);
}
}
创建TopicProducer.java,编写代码,代码如下。
package com.wsy.boot.activemq.producer;
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;
@Component
public class TopicProducer {
@Autowired
private JmsMessagingTemplate jmsMessagingTemplate;
@Autowired
private Topic topic;
/**
* 每间隔3秒钟执行一次
*/
@Scheduled(fixedDelay = 3000)
public void produceMessageScheduled() {
jmsMessagingTemplate.convertAndSend(topic, "SpringBoot整合ActiveMQ的Scheduled()方法");
}
}
创建Main.java,编写代码,代码如下。
package com.wsy.boot.activemq;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
}
来源:CSDN
作者:王劭阳
链接:https://blog.csdn.net/qq_36059561/article/details/103844020