SpringBoot整合ActiveMQ之Topic

SpringBoot整合ActiveMQ之Topic

注意:

不要忘记在启动类中添加@EnableJms启动消息队列注解

pom.xml依赖

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

application.properties

spring.activemq.broker-url=tcp://127.0.0.1:61616
#用户名
spring.activemq.user=admin
#密码
spring.activemq.password=admin
#true 表示使用内置的MQ,false则连接服务器
spring.activemq.in-memory=false
#信任所有的包
spring.activemq.packages.trust-all=true
#true表示使用连接池;false时,每发送一条数据创建一个连接
#是否替换默认的连接池,使用ActiveMQ的连接池需引入的依赖
spring.activemq.pool.enabled=false
#连接池最大连接数
spring.activemq.pool.max-connections=10
#空闲的连接过期时间,默认为30秒
spring.activemq.pool.idle-timeout=30000
#强制的连接过期时间,与idleTimeout的区别在于:idleTimeout是在连接空闲一段时间失效,而expiryTimeout不管当前连接的情况,只要达到指定时间就失效。默认为0,never
spring.activemq.pool.expire-timeout=0
#默认情况下activemq提供的是queue模式,若要使用topic模式需要配置下面配置
#spring.jms.pub-sub-domain=false
spring.jms.pub-sub-domain=true
#自己定义的Topic名称
mytopic=boot-active-mq

配置类

@Component
@EnableJms
public class Topic_ConfigBean {
    
    
    //读自己定义的topic名称的值
    @Value("${mytopic}")
    private String mytopic;

    @Bean //<bean id="" class="">
    public Topic topic() {
    
    
        return new ActiveMQTopic(mytopic);
    }
}

生产者

@Component
public class Topic_Producer {
    
    
    @Autowired
    private JmsMessagingTemplate jmsMessagingTemplate;
    @Autowired
    private Topic topic;
    public void product_Topic(){
    
    
        jmsMessagingTemplate.convertAndSend(topic,"********消息主题:"+ UUID.randomUUID().toString().substring(0,6));
    }
    @Scheduled(fixedDelay = 3000)
    public void product_Scheduled_Topic(){
    
    
        jmsMessagingTemplate.convertAndSend(topic, "scheduled消息主题:"+UUID.randomUUID().toString().substring(0,6));
        System.out.println("scheduled topic send ok");
    }
}

消费者

@Component
public class Topic_Consumer {
    
    
    @JmsListener(destination = "${mytopic}")
    public void recieve(TextMessage textMessage) throws JMSException {
    
    
        System.out.println("接收到topic消息-->"+textMessage.getText());
    }
}

主启动类

@SpringBootApplication
/**
 * 启动消息队列
 */
@EnableJms
@EnableScheduling
public class ActivemqApplication {
    
    

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

}

猜你喜欢

转载自blog.csdn.net/qq_38530648/article/details/108872050