阿里云-云小站(无限量代金券发放中)
【腾讯云】云服务器、云数据库、COS、CDN、短信等热卖云产品特惠抢购

集成Artemis

29次阅读
没有评论

共计 1499 个字符,预计需要花费 4 分钟才能阅读完成。

ActiveMQ Artemis 是一个 JMS 服务器,在集成 JMS 一节中我们已经详细讨论了如何在 Spring 中集成 Artemis,本节我们讨论如何在 Spring Boot 中集成 Artemis。

我们还是以实际工程为例,创建一个 springboot-jms 工程,引入的依赖除了 spring-boot-starter-webspring-boot-starter-jdbc 等以外,新增spring-boot-starter-artemis

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

同样无需指定版本号。

如何创建 Artemis 服务器我们已经在集成 JMS 一节中详细讲述了,此处不再重复。创建 Artemis 服务器后,我们在 application.yml 中加入相关配置:

spring:
  artemis:
    # 指定连接外部 Artemis 服务器,而不是启动嵌入式服务:
    mode: native
    # 服务器地址和端口号:
    host: 127.0.0.1
    port: 61616
    # 连接用户名和口令由创建 Artemis 服务器时指定:
    user: admin
    password: password

和 Spring 版本的 JMS 代码相比,使用 Spring Boot 集成 JMS 时,只要引入了 spring-boot-starter-artemis,Spring Boot 会自动创建 JMS 相关的ConnectionFactoryJmsListenerContainerFactoryJmsTemplate 等,无需我们再手动配置了。

发送消息时只需要引入JmsTemplate

@Component
public class MessagingService {@Autowired
    JmsTemplate jmsTemplate;

    public void sendMailMessage() throws Exception {String text = "...";
        jmsTemplate.send("jms/queue/mail", new MessageCreator() {public Message createMessage(Session session) throws JMSException {return session.createTextMessage(text);
            }
        });
    }
}

接收消息时只需要标注@JmsListener

@Component
public class MailMessageListener {final Logger logger = LoggerFactory.getLogger(getClass());

    @JmsListener(destination = "jms/queue/mail", concurrency = "10")
    public void onMailMessageReceived(Message message) throws Exception {logger.info("received message:" + message);
    }
}

可见,应用程序收发消息的逻辑和 Spring 中使用 JMS 完全相同,只是通过 Spring Boot,我们把工程简化到只需要设定 Artemis 相关配置。

练习

在 Spring Boot 中使用 Artemis。

下载练习

小结

在 Spring Boot 中使用 Artemis 作为 JMS 服务时,只需引入 spring-boot-starter-artemis 依赖,即可直接使用 JMS。

正文完
星哥说事-微信公众号
post-qrcode
 0
星锅
版权声明:本站原创文章,由 星锅 于2024-08-05发表,共计1499字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
【腾讯云】推广者专属福利,新客户无门槛领取总价值高达2860元代金券,每种代金券限量500张,先到先得。
阿里云-最新活动爆款每日限量供应
评论(没有评论)
验证码
【腾讯云】云服务器、云数据库、COS、CDN、短信等云产品特惠热卖中