SpringBoot具体整合ActiveMQ可参考:SpringBoot2.0应用(二):SpringBoot2.0整合ActiveMQ

ActiveMQ自动注入

当项目中存在javax.jms.Messageorg.springframework.jms.core.JmsTemplate着两个类时,SpringBoot将ActiveMQ需要使用到的对象注册为Bean,供项目注入使用。一起看一下JmsAutoConfiguration类。

@Configuration
@ConditionalOnClass({ Message.class, JmsTemplate.class })
@ConditionalOnBean(ConnectionFactory.class)
@EnableConfigurationProperties(JmsProperties.class)
@Import(JmsAnnotationDrivenConfiguration.class)
public class JmsAutoConfiguration { @Configuration
protected static class JmsTemplateConfiguration {
......
@Bean
@ConditionalOnMissingBean
@ConditionalOnSingleCandidate(ConnectionFactory.class)
public JmsTemplate jmsTemplate(ConnectionFactory connectionFactory) {
PropertyMapper map = PropertyMapper.get();
JmsTemplate template = new JmsTemplate(connectionFactory);
template.setPubSubDomain(this.properties.isPubSubDomain());
map.from(this.destinationResolver::getIfUnique).whenNonNull()
.to(template::setDestinationResolver);
map.from(this.messageConverter::getIfUnique).whenNonNull()
.to(template::setMessageConverter);
mapTemplateProperties(this.properties.getTemplate(), template);
return template;
}
......
} @Configuration
@ConditionalOnClass(JmsMessagingTemplate.class)
@Import(JmsTemplateConfiguration.class)
protected static class MessagingTemplateConfiguration { @Bean
@ConditionalOnMissingBean
@ConditionalOnSingleCandidate(JmsTemplate.class)
public JmsMessagingTemplate jmsMessagingTemplate(JmsTemplate jmsTemplate) {
return new JmsMessagingTemplate(jmsTemplate);
} } }

RabbitAutoConfiguration主要注入了jmsMessagingTemplatejmsTemplate

RabbitAutoConfiguration同时导入了RabbitAnnotationDrivenConfiguration,注入了jmsListenerContainerFactory

消息发送

以下面的发送为例:

    jmsMessagingTemplate.convertAndSend(this.queue, msg);

这个方法会先对消息进行转换,预处理,最终通过调用JmsTemplate的doSend实现消息发送的。

	protected void doSend(Session session, Destination destination, MessageCreator messageCreator)
throws JMSException {
Assert.notNull(messageCreator, "MessageCreator must not be null");
MessageProducer producer = createProducer(session, destination);
try {
Message message = messageCreator.createMessage(session);
doSend(producer, message);
if (session.getTransacted() && isSessionLocallyTransacted(session)) {
JmsUtils.commitIfNecessary(session);
}
}
finally {
JmsUtils.closeMessageProducer(producer);
}
}

首先创建一个MessageProducer的实例,接着将最初的org.springframework.messaging.Message转换成javax.jms.Message,再将消息委托给producer进行发送。

消息接收

先看一个消费的事例:

@Component
public class Consumer {
@JmsListener(destination = "sample.queue")
public void receiveQueue(String text) {
System.out.println(text);
}
}

SpringBoot会去解析@JmsListener,具体实现在JmsListenerAnnotationBeanPostProcessorpostProcessAfterInitialization方法。

	public Object postProcessAfterInitialization(final Object bean, String beanName) throws BeansException {
if (!this.nonAnnotatedClasses.contains(bean.getClass())) {
Class<?> targetClass = AopProxyUtils.ultimateTargetClass(bean);
Map<Method, Set<JmsListener>> annotatedMethods = MethodIntrospector.selectMethods(targetClass,
(MethodIntrospector.MetadataLookup<Set<JmsListener>>) method -> {
Set<JmsListener> listenerMethods = AnnotatedElementUtils.getMergedRepeatableAnnotations(
method, JmsListener.class, JmsListeners.class);
return (!listenerMethods.isEmpty() ? listenerMethods : null);
});
if (annotatedMethods.isEmpty()) {
this.nonAnnotatedClasses.add(bean.getClass());
}
else {
annotatedMethods.forEach((method, listeners) ->
listeners.forEach(listener ->
processJmsListener(listener, method, bean)));
}
}
return bean;
}

SpringBoot根据注解找到了使用了@JmsListener注解的方法,当监听到ActiveMQ收到的消息时,会调用对应的方法。来看一下具体怎么进行listener和method的绑定的。

	protected void processJmsListener(JmsListener jmsListener, Method mostSpecificMethod, Object bean) {
Method invocableMethod = AopUtils.selectInvocableMethod(mostSpecificMethod, bean.getClass());
MethodJmsListenerEndpoint endpoint = createMethodJmsListenerEndpoint();
endpoint.setBean(bean);
endpoint.setMethod(invocableMethod);
endpoint.setMostSpecificMethod(mostSpecificMethod);
endpoint.setMessageHandlerMethodFactory(this.messageHandlerMethodFactory);
endpoint.setEmbeddedValueResolver(this.embeddedValueResolver);
endpoint.setBeanFactory(this.beanFactory);
endpoint.setId(getEndpointId(jmsListener));
endpoint.setDestination(resolve(jmsListener.destination()));
if (StringUtils.hasText(jmsListener.selector())) {
endpoint.setSelector(resolve(jmsListener.selector()));
}
if (StringUtils.hasText(jmsListener.subscription())) {
endpoint.setSubscription(resolve(jmsListener.subscription()));
}
if (StringUtils.hasText(jmsListener.concurrency())) {
endpoint.setConcurrency(resolve(jmsListener.concurrency()));
} JmsListenerContainerFactory<?> factory = null;
String containerFactoryBeanName = resolve(jmsListener.containerFactory());
if (StringUtils.hasText(containerFactoryBeanName)) {
Assert.state(this.beanFactory != null, "BeanFactory must be set to obtain container factory by bean name");
try {
factory = this.beanFactory.getBean(containerFactoryBeanName, JmsListenerContainerFactory.class);
}
catch (NoSuchBeanDefinitionException ex) {
throw new BeanInitializationException("Could not register JMS listener endpoint on [" +
mostSpecificMethod + "], no " + JmsListenerContainerFactory.class.getSimpleName() +
" with id '" + containerFactoryBeanName + "' was found in the application context", ex);
}
} this.registrar.registerEndpoint(endpoint, factory);
}

先设置endpoint的相关属性,再获取jmsListenerContainerFactory,最后将endpoint注册到jmsListenerContainerFactory


本篇到此结束,如果读完觉得有收获的话,欢迎点赞、关注、加公众号【贰级天災】,查阅更多精彩历史!!!

SpringBoot2.0源码分析(二):整合ActiveMQ分析的更多相关文章

  1. jmeter4.0 源码编译 二次开发

    准备: 1.jmeter4.0源码 - apache-jmeter-4.0_src.zip 2.IDE Eclipse - Oxygen.3 Release (4.7.3) 3.JDK - 1.8.0 ...

  2. SpringBoot2.0源码分析(三):整合RabbitMQ分析

    SpringBoot具体整合rabbitMQ可参考:SpringBoot2.0应用(三):SpringBoot2.0整合RabbitMQ RabbitMQ自动注入 当项目中存在org.springfr ...

  3. SpringBoot2.0源码分析(一):SpringBoot简单分析

    SpringBoot2.0简单介绍:SpringBoot2.0应用(一):SpringBoot2.0简单介绍 本系列将从源码角度谈谈SpringBoot2.0. 先来看一个简单的例子 @SpringB ...

  4. SpringBoot2.0源码分析(四):spring-data-jpa分析

    SpringBoot具体整合rabbitMQ可参考:SpringBoot2.0应用(四):SpringBoot2.0之spring-data-jpa JpaRepositories自动注入 当项目中存 ...

  5. vue2.0 源码解读(二)

    小伞最近比较忙,阅读源码的速度越来越慢了 最近和朋友交流的时候,发现他们对于源码的目录结构都不是很清楚 红色圈子内是我们需要关心的地方 compiler  模板编译部分 core 核心实现部分 ent ...

  6. AFNetworking2.0源码解析<二>

    本篇我们继续来看看AFNetworking的下一个模块 — AFURLRequestSerialization.   AFURLRequestSerialization用于帮助构建NSURLReque ...

  7. [Android FrameWork 6.0源码学习] Window窗口类分析

    了解这一章节,需要先了解LayoutInflater这个工具类,我以前分析过:http://www.cnblogs.com/kezhuang/p/6978783.html Window是Activit ...

  8. webpack4.0源码解析之esModule打包分析

    入口文件index.js采用esModule方式导入模块文件,非入口文件index1.js分别采用CommonJS和esmodule规范进行导出. 首先,init之后创建一个简单的webpack基本的 ...

  9. AFNetworking (3.1.0) 源码解析 <二>

    这次讲解AFHTTPSessionManager类,按照顺序还是先看.h文件,注释中写到AFHTTPSessionManager是AFURLSessionManager的子类,并且带有方便的HTTP请 ...

随机推荐

  1. CentOS 系统 git clone出错

    CentOS 操作系统 安装npm git clone 项目时出现类似如下错误: fatal: unable to access 'https://github.com/creationix/nvmg ...

  2. stc15w wave

    1. 定时器和延时 #include "15W4KxxS4.h" #define FOSC 12000000 #define CLK (65536-FOSC/2/12/1000) ...

  3. jquery 表单校验

    <link type="text/css" href="<%=basepath%>css/form/validate.css" rel=&qu ...

  4. 创建.NET core的守护进程

    http://www.cnblogs.com/savorboard/p/dotnetcore-supervisor.html

  5. java crach 日志解析

    在java开发中,或许会出现如下错误,这种错误大多出现在开发中涉及本地代码的地方. ## A fatal error has been detected by the Java Runtime Env ...

  6. 2019.03.01 bzoj3075: [Usaco2013]Necklace(kmp+dp)

    传送门 题意简述:给出S,TS,TS,T两个字串,∣S∣≤10000,∣T∣≤1000|S|\le10000,|T|\le1000∣S∣≤10000,∣T∣≤1000,问至少从SSS中删去几个字符能够 ...

  7. 参考文献bib管理

    比如在IEEE模板中,在当前目录添加 bib 文件reference.bib 在 \end{document} 之前加入 \bibliographystyle{IEEEtran} \bibliogra ...

  8. Latex小技巧

    最近由于离散数学课程作业的需要, 使用$\LaTeX$写pdf报告, 积累了一些$\LaTeX$小技巧, 以后还会陆续补充. 1. 查看某个包的使用手册, 在命令行中输入texdoc XXX, 其中X ...

  9. django自定义user认证系统

    第一种,彻底推翻django的user认证系统,重新定义我们想要的字段 from django.contrib.auth.models import AbstractBaseUser,Permissi ...

  10. Visual Studio 代码片段

    管理界面 打开 工具 >> 代码片段管理器 界面 使用步骤 选择对应语言. 选择一个片段的文件夹. 打开该文件夹的位置. 复制任意一个片段. 对复制出来的片段进行修改.(具体修改内容见例子 ...