ActiveMQ

xinglun 2020-06-14

添加jar包依赖

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

<!--消息队列连接池-->
<dependency>
    <groupId>org.apache.activemq</groupId>
    <artifactId>activemq-pool</artifactId>
    <version>5.15.0</version>
</dependency>

添加spring boot配置

spring.activemq.broker-url=tcp://192.168.1.133:61616
spring.activemq.user=admin
spring.activemq.password=admin
#默认情况下activemq提供的是queue模式,若要使用topic模式需要配置下面配置
spring.jms.pub-sub-domain=true

创建ActiveMQ配置类

@Configuration
@EnableJms
public class JmsConfig {

    private static final String QUEUE_NAME = "active.queue";
     
    private static final String TOPIC_NAME = "active.topic";
 
    @Bean
    public Queue queue(){
        return new ActiveMQQueue(QUEUE_NAME);
    }
 
    @Bean
    public Topic topic(){
        return new ActiveMQTopic(TOPIC_NAME);
    }
}

一对一(队列):发送的消息只能由一个消费者接收

//提供者
@Component
public class ActiveMQQueueProducer {

    @Autowired
    private JmsMessagingTemplate jmsMessagingTemplate;
    @Autowired
    private Queue queue;

    public void sendQueueMsg(String msg) {
        this.jmsMessagingTemplate.convertAndSend(this.queue, msg);
    }

}
//消费者
ckage org.huqi.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.jms.annotation.JmsListener;

import javax.jms.TextMessage;

@Configuration
public class Que_comsumer {
    @JmsListener(destination = "active.queue")
    public void recive(TextMessage msg) throws  Exception{

       System.out.print(msg.getText().toString());
    }
}

发布订阅:及时接收,如果超过时候后就无法接收到消息

//提供者
@Component
public class ActiveMQTopicPublisher  {

    @Autowired
    private JmsMessagingTemplate jmsMessagingTemplate;

    @Autowired
    private Topic topic;

    public void sendTopicMsg(String msg) {
        System.out.println("发布信息:" + msg);
        this.jmsMessagingTemplate.convertAndSend(this.topic, msg);
    }

}
//消费者
@Component
public class ActiveMQTopicSubscriber {
    /**
     * 监听和读取topic消息
     * @param message
     */
    @JmsListener(destination = "active.topic")
    public void readActiveTopic(String message) {
        System.out.println("接受到:" + message);
    }
}

ActiveMQ无法写入对象解决,在spring boot配置文件中添加配置

#将所有对象都加入jsm白名单中
#允许所有包写入
spring.activemq.packages.trust-all=true


#指定包中的类加入白名单
spring.activemq.packages.trusted=org.huqi.bean

相关推荐