JMS 消息服务

JMS  是基于消息代理的规范,而ActiveMQ,HornetQ 是一个JMS 消息代理的实现

AMQP 也是一个消息代理的规范,但它不仅兼容JMS 还支持跨语言和跨平台。AMQP 的主要实现有RabbitMQ

队列/主题:点对点/发布与订阅

消息代理:message-broker

目的地:destination

需要实现:connectionFactory

spring 支持:@JmsListenner、@RabbitListener

开启:@EnableJms、@EnableRabbit

springboot:自动配置,实现ActiveMQ、HornetQ

实现ActiveMQConnectionFactory、JmsTemplate

安装:

docker search activemq

docker pull cloudesire/activemq

docker run -d -p 61616:61616 -p 8161:8161 cloudesire/activemq --name activemq

8161 端口为管理界面映射端口。

http访问:localhost:8161

添加依赖(使用activeMQ):

配置activemq

# activeMQ
spring.activemq.broker-url=tcp://localhost:61616
spring.activemq.user=
spring.activemq.password=
spring.activemq.in-memory=true
spring.activemq.pool.enabled=false

添加依赖

    implementation 'org.springframework:spring-jms'
    implementation 'org.apache.activemq:activemq-client'
    implementation 'org.apache.activemq:activemq-broker'
    implementation 'javax.jms:javax.jms-api'

定义消息

/**
 * JMS 实现creator 接口
 * 消息定义
 */
public class Msg implements MessageCreator {
    @Override
    public Message createMessage(Session session) throws JMSException {
        return session.createTextMessage("测试消息");
    }
}

消息监听

@Component
public class JmsListener {

    /**
     * 定义监听业务处理
     * 定义地址名称为my-destination
     * @param msg
     */
    @org.springframework.jms.annotation.JmsListener(destination = "my-destination")
    public void receoveMessage(String msg){
        System.out.println("接收到"+msg);
    }
}

发送消息

    /**
     * 注入jsm模版bean
     */
    @Autowired
    JmsTemplate jmsTemplate;

    @Override
    public void run(String... args) throws Exception {
        // 启动后执行发送消息到目的地
        jmsTemplate.send("my-destination",new Msg());
    }
原文地址:https://www.cnblogs.com/jony-it/p/11490559.html