ActiveMQ笔记42-SpringBoot整合ActiveMQ之主题生产者

纵然是瞬间 提交于 2020-01-12 09:12:04

新建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);
    }
}

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!