014 使用JMS处理消息

原文

https://spring.io/guides/gs/messaging-jms/

直译

创建一个消息接收器
Spring提供了向任何POJO发布消息的方法。

在本指南中,您将了解如何通过JMS消息代理发送消息。首先,让我们创建一个非常简单的POJO,它体现了电子邮件的细节。付款说明,我们不会发送电子邮件。我们只是将详细信息从一个地方发送到另一个地方,以便在邮件中发送什么内容。

src/main/java/hello/Email.java

package hello;

public class Email {

    private String to;
    private String body;

    public Email() {
    }

    public Email(String to, String body) {
        this.to = to;
        this.body = body;
    }

    public String getTo() {
        return to;
    }

    public void setTo(String to) {
        this.to = to;
    }

    public String getBody() {
        return body;
    }

    public void setBody(String body) {
        this.body = body;
    }

    @Override
    public String toString() {
        return String.format("Email{to=%s, body=%s}", getTo(), getBody());
    }

}

这个POJO非常简单,包含两个字段to和body,以及假设的getter和setter集合。

从这里,您可以定义消息接收器:

src/main/java/hello/Receiver.java

package hello;

import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;

@Component
public class Receiver {

    @JmsListener(destination = "mailbox", containerFactory = "myFactory")
    public void receiveMessage(Email email) {
        System.out.println("Received <" + email + ">");
    }

}

Receiver也被称为消息驱动的POJO。正如您在上面的代码中所看到的,不需要实现任何特定的接口或方法具有任何特定的名称。此外,该方法可以具有非常灵活的签名。请特别注意,此类在JMS API上没有导入。

该JmsListener注解定义的名称Destination,该方法应该听和参考JmsListenerContainerFactory用于创建基础消息侦听容器。严格地说,除非您需要自定义容器的构建方式,否则不需要最后一个属性,因为Spring Boot会在必要时注册默认工厂。

该参考文档涵盖得更详细。

使用Spring发送和接收JMS消息
接下来,连接发送器和接收器。

src/main/java/hello/Application.java

package hello;

import javax.jms.ConnectionFactory;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jms.DefaultJmsListenerContainerFactoryConfigurer;
import org.springframework.context.ConfigurableApplicationContext;
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.core.JmsTemplate;
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 Application {

    @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 // Serialize message content to json using TextMessage
    public MessageConverter jacksonJmsMessageConverter() {
        MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter();
        converter.setTargetType(MessageType.TEXT);
        converter.setTypeIdPropertyName("_type");
        return converter;
    }

    public static void main(String[] args) {
        // Launch the application
        ConfigurableApplicationContext context = SpringApplication.run(Application.class, args);

        JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class);

        // Send a message with a POJO - the template reuse the message converter
        System.out.println("Sending an email message.");
        jmsTemplate.convertAndSend("mailbox", new Email("info@example.com", "Hello"));
    }

}

@SpringBootApplication 是一个便利注释,添加了以下所有内容:

  • @Configuration 标记该类作为应用程序上下文的bean定义的来源。

  • @EnableAutoConfiguration 告诉Spring Boot开始根据类路径设置,其他bean和各种属性设置添加bean。

  • 通常你会添加@EnableWebMvc一个Spring MVC应用程序,但Spring Boot会在类路径上看到spring-webmvc时自动添加它。这会将应用程序标记为Web应用程序并激活关键行为,例如设置a DispatcherServlet。

  • @ComponentScan告诉Spring在包中寻找其他组件,配置和服务hello,允许它找到控制器。

该main()方法使用Spring Boot的SpringApplication.run()方法启动应用程序。您是否注意到没有一行XML?也没有web.xml文件。此Web应用程序是100%纯Java,您无需处理配置任何管道或基础结构。

@EnableJms触发发现带注释的方法@JmsListener,在封面下创建消息监听器容器。

为清楚起见,我们还定义了一个在接收器注释中myFactory引用的bean JmsListener。因为我们使用DefaultJmsListenerContainerFactoryConfigurerSpring Boot提供的基础结构,所以JmsMessageListenerContainer它与默认情况下引导创建的基础结构相同。

默认MessageConverter是能够转换只有基本类型(例如String,Map,Serializable)我们Email是不是Serializable故意的。我们想要使用Jackson并以文本格式将内容序列化为json(即作为a TextMessage)。Spring Boot将检测a的存在,MessageConverter并将其与默认值JmsTemplate和任何JmsListenerContainerFactory创建者相关联DefaultJmsListenerContainerFactoryConfigurer。

JmsTemplate使消息发送到JMS目的地变得非常简单。在mainrunner方法中,启动后,您可以使用jmsTemplate发送EmailPOJO。因为我们的自定义MessageConverter已自动关联到它,所以只会生成一个json文档TextMessage。

您没有看到定义的两个bean是JmsTemplate和ConnectionFactory。这些是由Spring Boot自动创建的。在这种情况下,ActiveMQ代理运行嵌入式。

默认情况下,Spring Boot会创建一个JmsTemplate配置为通过将pubSubDomain设置为false 来传输到队列。在也被配置是相同的。要覆盖,请通过Boot的属性设置(内部或环境变量)进行设置。然后确保接收容器具有相同的设置。JmsMessageListenerContainerspring.jms.isPubSubDomain=trueapplication.properties

Spring JmsTemplate可以通过它的receive方法直接接收消息,但这只能同步工作,这意味着它会阻塞。这就是为什么我们建议您使用侦听器容器,例如DefaultMessageListenerContainer使用基于缓存的连接工厂,这样您就可以异步使用消息并以最大的连接效率。

构建可执行的JAR

您可以使用Gradle或Maven从命令行运行该应用程序。或者,您可以构建一个包含所有必需依赖项,类和资源的可执行JAR文件,并运行该文件。这使得在整个开发生命周期中,跨不同环境等将服务作为应用程序发布,版本和部署变得容易。

如果您使用的是Gradle,则可以使用./gradlew bootRun。或者您可以使用构建JAR文件./gradlew build。然后你可以运行JAR文件:

java -jar build / libs / gs-messaging-jms-0.1.0.jar

如果您使用的是Maven,则可以使用该应用程序运行该应用程序./mvnw spring-boot:run。或者您可以使用构建JAR文件./mvnw clean package。然后你可以运行JAR文件:

java -jar target / gs-messaging-jms-0.1.0.jar

上面的过程将创建一个可运行的JAR。您也可以选择构建经典WAR文件。
当它运行时,埋在所有日志记录中,你应该看到这些消息:

Sending an email message.
Received <Email{to=info@example.com, body=Hello}>

摘要

恭喜!您刚刚开发了基于JMS的消息的发布者和使用者。

扩展知识

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值