Spring Boot JMSTemplate 嵌入ActiveMQ使用教程

位置:首页>文章>详情   分类: 教程分享 > Java教程   阅读(880)   2023-03-28 11:29:14
       习使用嵌入式ActiveMQ配置Spring Boot应用程序,以便在JMSTemplate 的帮助下发送和接收JMS消息。
 

项目结构

请在 Eclipse 中创建一个 Maven 应用程序并创建下面给定的文件夹结构。
Spring Boot JMSTemplate - 项目结构
Spring Boot JMSTemplate – 项目结构

要运行该示例,运行时需要 Java 1.8。

 

Maven 配置

pom.xml使用 Spring Boot 和 ActiveMQ 依赖项更新文件。此外,我们将需要Jackson进行对象到 JSON 的转换。

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd;">
    <modelVersion>4.0.0</modelVersion>
 
    <groupId>com.howtodoinjava.demo</groupId>
    <artifactId>SpringJMSTemplate</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
 
    <name>SpringJMSTemplate</name>
    <url>http://maven.apache.org</url>
 
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.2.RELEASE</version>
    </parent>
 
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
    </properties>
 
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-activemq</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.activemq</groupId>
            <artifactId>activemq-broker</artifactId>
        </dependency>
 
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </dependency>
    </dependencies>
</project>

@EnableJms 和 JmsListenerContainerFactory 配置

通过使用注释对其进行@SpringBootApplication注释来创建 Spring Boot 应用程序类。在类中添加此代码。

import javax.jms.ConnectionFactory;
 
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jms.DefaultJmsListenerContainerFactoryConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.jms.annotation.EnableJms;
import org.springframework.jms.config.DefaultJmsListenerContainerFactory;
import org.springframework.jms.config.JmsListenerContainerFactory;
import org.springframework.jms.support.converter.MappingJackson2MessageConverter;
import org.springframework.jms.support.converter.MessageConverter;
import org.springframework.jms.support.converter.MessageType;
 
@SpringBootApplication
@EnableJms
public class JMSApplication 
{
    @Bean
    public JmsListenerContainerFactory<?> myFactory(
                            ConnectionFactory connectionFactory,
                            DefaultJmsListenerContainerFactoryConfigurer configurer) 
    {
        DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
        // This provides all boot's default to this factory, including the message converter
        configurer.configure(factory, connectionFactory);
        // You could still override some of Boot's default if necessary.
        return factory;
    }
 
    @Bean
    public MessageConverter jacksonJmsMessageConverter() 
    {
        MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter();
        converter.setTargetType(MessageType.TEXT);
        converter.setTypeIdPropertyName("_type");
        return converter;
    }
}
  • @SpringBootApplicationannotation 等价于 using @Configuration,@EnableAutoConfiguration以及@ComponentScan它们的默认属性。使用注解配置轻松配置 spring 应用程序是一种快捷方式。
  • @EnableJms启用@JmsListenerJmsListenerContainerFactory.
  • JmsListenerContainerFactory负责创建负责特定端点侦听容器。作为 的典型实现DefaultJmsListenerContainerFactory提供了底层MessageListenerContainer.
  • MappingJackson2MessageConverter用于将 a 的有效负载Message从序列化形式转换为类型化对象,反之亦然。
  • 我们已经配置了MessageType.TEXT. 此消息类型可用于传输基于文本的消息。当客户端收到 时TextMessage,它处于只读模式。如果此时客户端尝试写入消息,MessageNotWriteableException则会抛出 a。

带有 @JmsListener 的 JMS 消息接收器

消息接收器类是非常简单的类,具有带注释的单一方法@JmsListener@JmsListener允许您将托管 bean 的方法公开为 JMS 侦听器端点。
因此,每当配置的队列上有任何消息可用时(在此示例中,队列名称为“jms.message.endpoint”),receiveMessage将调用带注释的方法(即)。

@JmsListener 是一个可重复的注释,因此您可以在同一方法上多次使用它来将多个 JMS 目标注册到同一方法。

import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;
 
@Component
public class MessageReceiver {
 
    @JmsListener(destination = "jms.message.endpoint")
    public void receiveMessage(Message msg) 
    {
        System.out.println("Received " + msg );
    }
}

Message班是简单的POJO类。

import java.io.Serializable;
import java.util.Date;
 
public class Message implements Serializable {
 
    private static final long serialVersionUID = 1L;
     
    private Long id;
    private String content;
    private Date date;
 
    public Message() {
    }
 
    public Message(Long id, String content, Date date) {
        super();
        this.id = id;
        this.content = content;
        this.date = date;
    }
 
    public Long getId() {
        return id;
    }
 
    public void setId(Long id) {
        this.id = id;
    }
 
    public String getContent() {
        return content;
    }
 
    public void setContent(String content) {
        this.content = content;
    }
 
    public Date getDate() {
        return date;
    }
 
    public void setDate(Date date) {
        this.date = date;
    }
 
    @Override
    public String toString() {
        return "Message [id=" + id + ", content=" + content + ", date=" + date + "]";
    }
}

使用 JmsTemplate 发送消息

要发送 JMS 消息,您将需要JmsTemplate来自 spring 容器的 bean 类的引用。调用它的convertAndSend()方法来发送消息。

import java.util.Date;
 
import org.springframework.boot.SpringApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.jms.core.JmsTemplate;
 
public class Main 
{
    public static void main(String[] args) 
    {
        // Launch the application
        ConfigurableApplicationContext context = SpringApplication.run(JMSApplication.class, args);
 
        //Get JMS template bean reference
        JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class);
 
        // Send a message
        System.out.println("Sending a message.");
        jmsTemplate.convertAndSend("jms.message.endpoint", new Message(1001L, "test body", new Date()));
    }
}

演示
执行上述Main类的 main() 方法。这将启动 Spring boot 应用程序,然后向 queue 发送消息jms.message.endpoint
MessageReceiver.receiveMessage()已经在监听这个队列地址。所以消息将通过此方法接收,可以通过将其打印到控制台来验证。
在控制台中,输出将是这样的:

发送消息。
收到的消息 [id=1001, content=test body, date=Fri Jul 07 14:19:19 IST 2017]
显然,消息已成功发送和接收。这就是带有嵌入式 ActiveMQSpring JMSTemplate快速示例的全部内容。
地址:https://www.leftso.com/article/874.html

相关阅读

spring boot整合activemq。本博客将通过一个简单的例子讲解在spring boot中activemq如何作为消费者(Consumer )和如何在spring boot中消息提供者...
       习使用嵌入式ActiveMQ配置Spring Boot应用程序,以便在JMSTemplate 的帮助下发送和接收JMS消息
Java编程之Spring Boot通过JMSTemplate 整合ActiveMQ
Spring Boot MQTT协议通过spring boot整合apache artemis实现Java语言MQTT协议通信,搭建MQTT服务器可以参考上一篇 MQTT Java入门-搭建MQ...
Spring Boot validation整合hibernate validator实现数据验证,Spring Boot validation使用说明,Spring Boot validat...
spring boot又一个spring框架的经典项目,本文讲解spring boot入门的环境配置以及第一个项目,Spring Boot 入门教程
引言    通过之前spring boot mybatis 整合的讲解: spring boot mybaties整合  (spring boot mybaties 整合 基于Java注解方式写...
前言    本教程主要讲解spring boot如何整合 spring data elasticsearch 实现elasticsearch检索引擎的整合使用
Spring Boot 2.0,Spring框架的Spring Boot 中的Spring Boot Actuator变化讲解。并且了解如何在Spring Boot 2.0中使用Actuator...