Spring 应用合并之路(二):峰回路转,柳暗花明

作者:京东科技 李君

书接上文,前面在 Spring 应用合并之路(一):摸石头过河 介绍了几种不成功的经验,下面继续折腾…



四、仓库合并,独立容器

在经历了上面的尝试,在同事为啥不搞两个独立的容器提醒下,决定抛开 Spring Boot 内置的父子容器方案,完全自己实现父子容器。

如何加载 web 项目?

现在的难题只有一个:如何加载 web 项目?加载完成后,如何持续持有 web 项目?经过思考后,可以创建一个 boot 项目的 Spring Bean,在该 Bean 中加载并持有 web 项目的容器。由于 Spring Bean 默认是单例的,并且会伴随 Spring 容器长期存活,就可以保证 web 容器持久存活。结合 Spring 扩展点概览及实践 中介绍的 Spring 扩展点,有两个地方可以利用:



1.可以利用 ApplicationContextAware 获取 boot 容器的 ApplicationContext 实例,这样就可以实现自己实现的父子容器;

2.可以利用 ApplicationListener 获取 ContextRefreshedEvent 事件,该事件表示容器已经完成初始化,可以提供服务。在监听到该事件后,来进行 web 容器的加载。



思路确定后,代码实现就很简单了:



1package com.diguage.demo.boot.config; 2 3import org.slf4j.Logger; 4import org.slf4j.LoggerFactory; 5import org.springframework.beans.BeansException; 6import org.springframework.context.ApplicationContext; 7import org.springframework.context.ApplicationContextAware; 8import org.springframework.context.ApplicationEvent; 9import org.springframework.context.ApplicationListener; 10import org.springframework.context.event.ContextRefreshedEvent; 11import org.springframework.context.support.ClassPathXmlApplicationContext; 12import org.springframework.stereotype.Component; 13 14/** 15 * @author D瓜哥 · https://www.diguage.com 16 */ 17@Component 18public class WebLoaderListener implements ApplicationContextAware, 19 ApplicationListener<ApplicationEvent> { 20 private static final Logger logger = LoggerFactory.getLogger(WebLoaderListener.class); 21 22 /** 23 * 父容器,加载 boot 项目 24 */ 25 private static ApplicationContext parentContext; 26 27 /** 28 * 子容器,加载 web 项目 29 */ 30 private static ApplicationContext childContext; 31 32 @Override 33 public void setApplicationContext(ApplicationContext ctx) throws BeansException { 34 WebLoaderListener.parentContext = ctx; 35 } 36 37 @Override 38 public void onApplicationEvent(ApplicationEvent event) { 39 logger.info("receive application event: {}", event); 40 if (event instanceof ContextRefreshedEvent) { 41 WebLoaderListener.childContext = new ClassPathXmlApplicationContext( 42 new String[]{"classpath:web/spring-cfg.xml"}, 43 WebLoaderListener.parentContext); 44 } 45 } 46}

容器重复加载的问题

这次自己实现的父子容器,如同设想的那样,没有同名 Bean 的检查,省去了很多麻烦。但是,观察日志,会发现 com.diguage.demo.boot.config.WebLoaderListener#onApplicationEvent 方法被两次执行,也就是监听到了两次 ContextRefreshedEvent 事件,导致 web 容器会被加载两次。由于项目的 RPC 服务不能重复注册,第二次加载抛出异常,导致启动失败。

最初,怀疑是 web 容器,加载了 WebLoaderListener,但是跟踪代码,没有发现 childContext 容器中有 WebLoaderListener 的相关 Bean。

昨天做了个小实验,又调试了一下 Spring 的源代码,发现了其中的奥秘。直接贴代码吧:

SPRING/spring-context/src/main/java/org/springframework/context/support/AbstractApplicationContext.java



1/** 2 * Publish the given event to all listeners. 3 * <p>This is the internal delegate that all other {@code publishEvent} 4 * methods refer to. It is not meant to be called directly but rather serves 5 * as a propagation mechanism between application contexts in a hierarchy, 6 * potentially overridden in subclasses for a custom propagation arrangement. 7 * @param event the event to publish (may be an {@link ApplicationEvent} 8 * or a payload object to be turned into a {@link PayloadApplicationEvent}) 9 * @param typeHint the resolved event type, if known. 10 * The implementation of this method also tolerates a payload type hint for 11 * a payload object to be turned into a {@link PayloadApplicationEvent}. 12 * However, the recommended way is to construct an actual event object via 13 * {@link PayloadApplicationEvent#PayloadApplicationEvent(Object, Object, ResolvableType)} 14 * instead for such scenarios. 15 * @since 4.2 16 * @see ApplicationEventMulticaster#multicastEvent(ApplicationEvent, ResolvableType) 17 */ 18protected void publishEvent(Object event, @Nullable ResolvableType typeHint) { 19 Assert.notNull(event, "Event must not be null"); 20 ResolvableType eventType = null; 21 22 // Decorate event as an ApplicationEvent if necessary 23 ApplicationEvent applicationEvent; 24 if (event instanceof ApplicationEvent applEvent) { 25 applicationEvent = applEvent; 26 eventType = typeHint; 27 } 28 else { 29 ResolvableType payloadType = null; 30 if (typeHint != null && ApplicationEvent.class.isAssignableFrom(typeHint.toClass())) { 31 eventType = typeHint; 32 } 33 else { 34 payloadType = typeHint; 35 } 36 applicationEvent = new PayloadApplicationEvent<>(this, event, payloadType); 37 } 38 39 // Determine event type only once (for multicast and parent publish) 40 if (eventType == null) { 41 eventType = ResolvableType.forInstance(applicationEvent); 42 if (typeHint == null) { 43 typeHint = eventType; 44 } 45 } 46 47 // Multicast right now if possible - or lazily once the multicaster is initialized 48 if (this.earlyApplicationEvents != null) { 49 this.earlyApplicationEvents.add(applicationEvent); 50 } 51 else if (this.applicationEventMulticaster != null) { 52 this.applicationEventMulticaster.multicastEvent(applicationEvent, eventType); 53 } 54 55 // Publish event via parent context as well... 56 // 如果有父容器,则也将事件发布给父容器。 57 if (this.parent != null) { 58 if (this.parent instanceof AbstractApplicationContext abstractApplicationContext) { 59 abstractApplicationContext.publishEvent(event, typeHint); 60 } 61 else { 62 this.parent.publishEvent(event); 63 } 64 } 65}

publishEvent 方法的最后,如果父容器不为 null 的情况下,则也会向父容器广播容器的相关事件。

看到这里就清楚了,不是 web 容器持有了 WebLoaderListener 这个 Bean,而是 web 容器主动向父容器广播了 ContextRefreshedEvent 事件。

容器销毁

除了上述问题,还有一个问题需要思考:如何销毁 web 容器?如果不能销毁容器,会有一些意想不到的问题。比如,注册中心的 RPC 提供方不能及时销毁等等。

这里的解决方案也比较简单:同样基于事件监听,Spring 容器销毁会有 ContextClosedEvent 事件,在 WebLoaderListener 中监听该事件,然后调用 AbstractApplicationContext#close 方法就可以完成 Spring 容器的销毁工作。

父子容器加载及销毁

结合上面的所有论述,完整的代码如下:



1package com.diguage.demo.boot.config; 2 3import org.slf4j.Logger; 4import org.slf4j.LoggerFactory; 5import org.springframework.beans.BeansException; 6import org.springframework.context.ApplicationContext; 7import org.springframework.context.ApplicationContextAware; 8import org.springframework.context.ApplicationEvent; 9import org.springframework.context.ApplicationListener; 10import org.springframework.context.event.ContextClosedEvent; 11import org.springframework.context.event.ContextRefreshedEvent; 12import org.springframework.context.support.AbstractApplicationContext; 13import org.springframework.context.support.ClassPathXmlApplicationContext; 14import org.springframework.stereotype.Component; 15 16import java.util.Objects; 17 18/** 19 * 基于事件监听的 web 项目加载器 20 * 21 * @author D瓜哥 · https://www.diguage.com 22 */ 23@Component 24public class WebLoaderListener implements ApplicationContextAware, 25 ApplicationListener<ApplicationEvent> { 26 private static final Logger logger = LoggerFactory.getLogger(WebLoaderListener.class); 27 28 /** 29 * 父容器,加载 boot 项目 30 */ 31 private static ApplicationContext parentContext; 32 33 /** 34 * 子容器,加载 web 项目 35 */ 36 private static ClassPathXmlApplicationContext childContext; 37 38 @Override 39 public void setApplicationContext(ApplicationContext ctx) throws BeansException { 40 WebLoaderListener.parentContext = ctx; 41 } 42 43 /** 44 * 事件监听 45 * 46 * @author D瓜哥 · https://www.diguage.com 47 */ 48 @Override 49 public void onApplicationEvent(ApplicationEvent event) { 50 logger.info("receive application event: {}", event); 51 if (event instanceof ContextRefreshedEvent refreshedEvent) { 52 ApplicationContext context = refreshedEvent.getApplicationContext(); 53 if (Objects.equals(WebLoaderListener.parentContext, context)) { 54 // 加载 web 容器 55 WebLoaderListener.childContext = new ClassPathXmlApplicationContext( 56 new String[]{"classpath:web/spring-cfg.xml"}, 57 WebLoaderListener.parentContext); 58 } 59 } else if (event instanceof ContextClosedEvent) { 60 // 处理容器销毁事件 61 if (Objects.nonNull(WebLoaderListener.childContext)) { 62 synchronized (WebLoaderListener.class) { 63 if (Objects.nonNull(WebLoaderListener.childContext)) { 64 AbstractApplicationContext ctx = WebLoaderListener.childContext; 65 WebLoaderListener.childContext = null; 66 ctx.close(); 67 } 68 } 69 } 70 } 71 } 72}



五、参考资料

1.Spring 扩展点概览及实践 - "地瓜哥"博客网

2.Context Hierarchy with the Spring Boot Fluent Builder API

3.How to revert initial git commit?

点赞
收藏

评论区

加载中...

相关推荐

手把手带你开发starter,点对点带你讲解原理

在2012年10月,一个叫MikeYoungstrom的人在SpringJira中创建了一个功能请求,要求在SpringFramework中支持无容器Web应用程序体系结构,提出了在主容器引导Spring容器内配置Web容器服务;这件事情对SpringBoot的诞生应该说是起到了一定的推动作用。

spring源码解析

前言上篇我们介绍了spring容器加载的方式,并重点介绍了基于xml配置解析和注解扫描两种容器加载的方式,封装和注册beandefinition的过程。今天我们分享BeanDefinition注册后的另一个重要过程bean的实例化过程的源码。容器加载流程!spring源码解析spring容器加载源码(bean实

springboot使用之快捷打包部署

本篇关键知识点:Maven的assembly插件实现自定义打包部署(包含依赖jar包) 目前springboot项目的几种常见的部署方式。1\.使用docker容器去部署,将springboot的应用构建成一个dockerimage,然后通过容器去启动镜像,这种方式在

Tomcat的工作模式

Tomcat作为Servlet容器,有3种工作模式:独立的Servlet容器、进程内的Servlet容器和进程外的Servlet容器。1.独立的Servlet容器   独立的Servlet容器是Tomcat的默认模式。在这种模式下,Tomcat可以作为独立的JavaWeb服务器,Servlet容器作为构成Web服务器的一部分而存在。2.进

5 秒创建 k8s 集群

据说Google的数据中心里运行着超过20亿个容器,而且Google十年前就开始使用容器技术。最初,Google开发了一个叫Borg的系统(现在命令为Omega)来调度如此庞大数量的容器和工作负载。在积累了这么多年的经验后,Google决定重写这个容器管理系统,并将其贡献到开源社区,让全世界都能受益。这个项目就是Kuberne

Springboot基于assembly的服务化打包方案

  在使用assembly来打包springboot微服务项目前,我想说一说,目前springboot项目的几种常见的部署方式。1. 使用docker容器去部署,将springboot的应用构建成一个dockerimage,然后通过容器去启动镜像,这种方式在需要部署大规模的应用和应用扩展时是非常方便的,属于目前工业级的部署方案,但是需要掌握d