Spring 应用合并之路(二):峰回路转,柳暗花明 | 京东云技术团队

本文主要是介绍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 容器的加载。

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

package com.diguage.demo.boot.config;import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;/*** @author D瓜哥 · https://www.diguage.com*/
@Component
public class WebLoaderListener implements ApplicationContextAware,ApplicationListener<ApplicationEvent> {private static final Logger logger = LoggerFactory.getLogger(WebLoaderListener.class);/*** 父容器,加载 boot 项目*/private static ApplicationContext parentContext;/*** 子容器,加载 web 项目*/private static ApplicationContext childContext;@Overridepublic void setApplicationContext(ApplicationContext ctx) throws BeansException {WebLoaderListener.parentContext = ctx;}@Overridepublic void onApplicationEvent(ApplicationEvent event) {logger.info("receive application event: {}", event);if (event instanceof ContextRefreshedEvent) {WebLoaderListener.childContext = new ClassPathXmlApplicationContext(new String[]{"classpath:web/spring-cfg.xml"},WebLoaderListener.parentContext);}}
}

容器重复加载的问题

这次自己实现的父子容器,如同设想的那样,没有同名 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

/*** Publish the given event to all listeners.* <p>This is the internal delegate that all other {@code publishEvent}* methods refer to. It is not meant to be called directly but rather serves* as a propagation mechanism between application contexts in a hierarchy,* potentially overridden in subclasses for a custom propagation arrangement.* @param event the event to publish (may be an {@link ApplicationEvent}* or a payload object to be turned into a {@link PayloadApplicationEvent})* @param typeHint the resolved event type, if known.* The implementation of this method also tolerates a payload type hint for* a payload object to be turned into a {@link PayloadApplicationEvent}.* However, the recommended way is to construct an actual event object via* {@link PayloadApplicationEvent#PayloadApplicationEvent(Object, Object, ResolvableType)}* instead for such scenarios.* @since 4.2* @see ApplicationEventMulticaster#multicastEvent(ApplicationEvent, ResolvableType)*/
protected void publishEvent(Object event, @Nullable ResolvableType typeHint) {Assert.notNull(event, "Event must not be null");ResolvableType eventType = null;// Decorate event as an ApplicationEvent if necessaryApplicationEvent applicationEvent;if (event instanceof ApplicationEvent applEvent) {applicationEvent = applEvent;eventType = typeHint;}else {ResolvableType payloadType = null;if (typeHint != null && ApplicationEvent.class.isAssignableFrom(typeHint.toClass())) {eventType = typeHint;}else {payloadType = typeHint;}applicationEvent = new PayloadApplicationEvent<>(this, event, payloadType);}// Determine event type only once (for multicast and parent publish)if (eventType == null) {eventType = ResolvableType.forInstance(applicationEvent);if (typeHint == null) {typeHint = eventType;}}// Multicast right now if possible - or lazily once the multicaster is initializedif (this.earlyApplicationEvents != null) {this.earlyApplicationEvents.add(applicationEvent);}else if (this.applicationEventMulticaster != null) {this.applicationEventMulticaster.multicastEvent(applicationEvent, eventType);}// Publish event via parent context as well...// 如果有父容器,则也将事件发布给父容器。if (this.parent != null) {if (this.parent instanceof AbstractApplicationContext abstractApplicationContext) {abstractApplicationContext.publishEvent(event, typeHint);}else {this.parent.publishEvent(event);}}
}

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

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

容器销毁

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

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

父子容器加载及销毁

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

package com.diguage.demo.boot.config;import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;import java.util.Objects;/*** 基于事件监听的 web 项目加载器** @author D瓜哥 · https://www.diguage.com*/
@Component
public class WebLoaderListener implements ApplicationContextAware,ApplicationListener<ApplicationEvent> {private static final Logger logger = LoggerFactory.getLogger(WebLoaderListener.class);/*** 父容器,加载 boot 项目*/private static ApplicationContext parentContext;/*** 子容器,加载 web 项目*/private static ClassPathXmlApplicationContext childContext;@Overridepublic void setApplicationContext(ApplicationContext ctx) throws BeansException {WebLoaderListener.parentContext = ctx;}/*** 事件监听** @author D瓜哥 · https://www.diguage.com*/@Overridepublic void onApplicationEvent(ApplicationEvent event) {logger.info("receive application event: {}", event);if (event instanceof ContextRefreshedEvent refreshedEvent) {ApplicationContext context = refreshedEvent.getApplicationContext();if (Objects.equals(WebLoaderListener.parentContext, context)) {// 加载 web 容器WebLoaderListener.childContext = new ClassPathXmlApplicationContext(new String[]{"classpath:web/spring-cfg.xml"},WebLoaderListener.parentContext);}} else if (event instanceof ContextClosedEvent) {// 处理容器销毁事件if (Objects.nonNull(WebLoaderListener.childContext)) {synchronized (WebLoaderListener.class) {if (Objects.nonNull(WebLoaderListener.childContext)) {AbstractApplicationContext ctx = WebLoaderListener.childContext;WebLoaderListener.childContext = null;ctx.close();}}}}}
}

五、参考资料

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

2.Context Hierarchy with the Spring Boot Fluent Builder API

3.How to revert initial git commit?

作者:京东科技 李君

来源:京东云开发者社区 转载请注明来源

这篇关于Spring 应用合并之路(二):峰回路转,柳暗花明 | 京东云技术团队的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/576732

相关文章

JVM 的类初始化机制

前言 当你在 Java 程序中new对象时,有没有考虑过 JVM 是如何把静态的字节码(byte code)转化为运行时对象的呢,这个问题看似简单,但清楚的同学相信也不会太多,这篇文章首先介绍 JVM 类初始化的机制,然后给出几个易出错的实例来分析,帮助大家更好理解这个知识点。 JVM 将字节码转化为运行时对象分为三个阶段,分别是:loading 、Linking、initialization

Spring Security 基于表达式的权限控制

前言 spring security 3.0已经可以使用spring el表达式来控制授权,允许在表达式中使用复杂的布尔逻辑来控制访问的权限。 常见的表达式 Spring Security可用表达式对象的基类是SecurityExpressionRoot。 表达式描述hasRole([role])用户拥有制定的角色时返回true (Spring security默认会带有ROLE_前缀),去

浅析Spring Security认证过程

类图 为了方便理解Spring Security认证流程,特意画了如下的类图,包含相关的核心认证类 概述 核心验证器 AuthenticationManager 该对象提供了认证方法的入口,接收一个Authentiaton对象作为参数; public interface AuthenticationManager {Authentication authenticate(Authenti

Spring Security--Architecture Overview

1 核心组件 这一节主要介绍一些在Spring Security中常见且核心的Java类,它们之间的依赖,构建起了整个框架。想要理解整个架构,最起码得对这些类眼熟。 1.1 SecurityContextHolder SecurityContextHolder用于存储安全上下文(security context)的信息。当前操作的用户是谁,该用户是否已经被认证,他拥有哪些角色权限…这些都被保

Spring Security基于数据库验证流程详解

Spring Security 校验流程图 相关解释说明(认真看哦) AbstractAuthenticationProcessingFilter 抽象类 /*** 调用 #requiresAuthentication(HttpServletRequest, HttpServletResponse) 决定是否需要进行验证操作。* 如果需要验证,则会调用 #attemptAuthentica

Spring Security 从入门到进阶系列教程

Spring Security 入门系列 《保护 Web 应用的安全》 《Spring-Security-入门(一):登录与退出》 《Spring-Security-入门(二):基于数据库验证》 《Spring-Security-入门(三):密码加密》 《Spring-Security-入门(四):自定义-Filter》 《Spring-Security-入门(五):在 Sprin

Java架构师知识体认识

源码分析 常用设计模式 Proxy代理模式Factory工厂模式Singleton单例模式Delegate委派模式Strategy策略模式Prototype原型模式Template模板模式 Spring5 beans 接口实例化代理Bean操作 Context Ioc容器设计原理及高级特性Aop设计原理Factorybean与Beanfactory Transaction 声明式事物

百度/小米/滴滴/京东,中台架构比较

小米中台建设实践 01 小米的三大中台建设:业务+数据+技术 业务中台--从业务说起 在中台建设中,需要规范化的服务接口、一致整合化的数据、容器化的技术组件以及弹性的基础设施。并结合业务情况,判定是否真的需要中台。 小米参考了业界优秀的案例包括移动中台、数据中台、业务中台、技术中台等,再结合其业务发展历程及业务现状,整理了中台架构的核心方法论,一是企业如何共享服务,二是如何为业务提供便利。

中文分词jieba库的使用与实景应用(一)

知识星球:https://articles.zsxq.com/id_fxvgc803qmr2.html 目录 一.定义: 精确模式(默认模式): 全模式: 搜索引擎模式: paddle 模式(基于深度学习的分词模式): 二 自定义词典 三.文本解析   调整词出现的频率 四. 关键词提取 A. 基于TF-IDF算法的关键词提取 B. 基于TextRank算法的关键词提取

水位雨量在线监测系统概述及应用介绍

在当今社会,随着科技的飞速发展,各种智能监测系统已成为保障公共安全、促进资源管理和环境保护的重要工具。其中,水位雨量在线监测系统作为自然灾害预警、水资源管理及水利工程运行的关键技术,其重要性不言而喻。 一、水位雨量在线监测系统的基本原理 水位雨量在线监测系统主要由数据采集单元、数据传输网络、数据处理中心及用户终端四大部分构成,形成了一个完整的闭环系统。 数据采集单元:这是系统的“眼睛”,