ActiveMQ

Posted huqi96

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ActiveMQ相关的知识,希望对你有一定的参考价值。

添加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

 

以上是关于ActiveMQ的主要内容,如果未能解决你的问题,请参考以下文章

wildfly 实践5 ---分布式服务中的JMS服务访问

ActiveMQ的安全机制使用及其源代码分析 [转]

ActiveMQ——activemq的使用java代码实例

ActiveMQ入门系列二:入门代码实例(点对点模式)

ActiveMQ入门案例-生产者代码实现

ActiveMQ queue 代码示例