下面列出了怎么用org.springframework.context.event.ContextClosedEvent的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public void onApplicationEvent(ContextClosedEvent event) {
LOG.info("[Drivers] About to de-register drivers...");
Enumeration<Driver> drivers = DriverManager.getDrivers();
while (drivers.hasMoreElements()) {
Driver driver = drivers.nextElement();
LOG.info("[Drivers] De-registering {}", driver);
try {
DriverManager.deregisterDriver(driver);
} catch (SQLException e) {
LOG.error("Failed to deregister driver: {}", driver.getClass());
}
}
LOG.info("[Drivers] De-registered drivers.");
}
@Override
public void onApplicationEvent(ContextClosedEvent contextClosedEvent) {
if (this.connector == null) {
return;
}
this.connector.pause();
Executor executor = this.connector.getProtocolHandler().getExecutor();
if (executor instanceof ThreadPoolExecutor) {
try {
ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) executor;
threadPoolExecutor.shutdown();
if (!threadPoolExecutor.awaitTermination(waitTime, TimeUnit.SECONDS)) {
log.warn("Tomcat 进程在" + waitTime + " 秒内无法结束,尝试强制结束");
}
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
}
/**
* Listens ContextClosedEvent and Closes all async http connections
*/
@Bean
ApplicationListener<?> applicationListener() {
return new SmartApplicationListener() {
@Override
public int getOrder() { return 0; }
@Override
public boolean supportsEventType(Class<? extends ApplicationEvent> eventType) {
return ContextClosedEvent.class.isAssignableFrom(eventType);
}
@Override
public boolean supportsSourceType(Class<?> sourceType) { return true; }
@Override
public void onApplicationEvent(ApplicationEvent event) { Closeables.close(proxyInstance); }
};
}
public static void main(String[] args) throws IOException {
GenericApplicationContext context = new GenericApplicationContext();
context.addApplicationListener(new ApplicationListener<ContextClosedEvent>() {
@Override
public void onApplicationEvent(ContextClosedEvent event) {
System.out.printf("[线程 %s] ContextClosedEvent 处理\n", Thread.currentThread().getName());
}
});
// 刷新 Spring 应用上下文
context.refresh();
// 注册 Shutdown Hook
context.registerShutdownHook();
System.out.println("按任意键继续并且关闭 Spring 应用上下文");
System.in.read();
// 关闭 Spring 应用(同步)
context.close();
}
@Override
public void onApplicationEvent(ApplicationEvent event) {
if (event instanceof ApplicationEnvironmentPreparedEvent) {
LOG.debug("初始化环境变量");
} else if (event instanceof ApplicationPreparedEvent) {
LOG.debug("初始化完成");
LOG.debug("初始GameData策划数据");
ConfigManager.loadGameData(this.configPath);
} else if (event instanceof ContextRefreshedEvent) {
LOG.debug("应用刷新");
} else if (event instanceof ApplicationReadyEvent) {
LOG.debug("应用已启动完成");
} else if (event instanceof ContextStartedEvent) {
LOG.debug("应用启动,需要在代码动态添加监听器才可捕获");
} else if (event instanceof ContextStoppedEvent) {
LOG.debug("应用停止");
} else if (event instanceof ContextClosedEvent) {
ApplicationContext context = ((ContextClosedEvent) event).getApplicationContext();
rpcClient = context.getBean(RpcClient.class);
rpcClient.close();
LOG.error("应用关闭");
} else {
}
}
@Override
public void onApplicationEvent(ApplicationEvent event) {
if (event instanceof ApplicationEnvironmentPreparedEvent) {
LOG.debug("初始化环境变量");
} else if (event instanceof ApplicationPreparedEvent) {
LOG.debug("初始化完成");
LOG.debug("初始GameData策划数据");
String path = ApplicationEventListener.class.getResource("/gamedata").getFile();
ConfigManager.loadGameData(path);
} else if (event instanceof ContextRefreshedEvent) {
LOG.debug("应用刷新");
} else if (event instanceof ApplicationReadyEvent) {
LOG.debug("应用已启动完成");
} else if (event instanceof ContextStartedEvent) {
LOG.debug("应用启动,需要在代码动态添加监听器才可捕获");
} else if (event instanceof ContextStoppedEvent) {
LOG.debug("应用停止");
} else if (event instanceof ContextClosedEvent) {
ApplicationContext applicationContext = ((ContextClosedEvent) event).getApplicationContext();
grpcClient = applicationContext.getBean(GrpcClient.class);
grpcClient.close();
LOG.debug("应用关闭");
}
}
@Test
public void startUpWithFailure() throws Exception {
//shutting the service down
workerManager.onApplicationEvent(mock(ContextClosedEvent.class));
assertThat(workerManager.isUp()).isFalse();
reset(workerNodeService);
doThrow(new RuntimeException("try 1"))
.doThrow(new RuntimeException("try 2"))
.doThrow(new RuntimeException("try 3"))
.doReturn("1")
.when(workerNodeService).up(CREDENTIAL_UUID, "version", "123");
//start again
workerManager.onApplicationEvent(mock(ContextRefreshedEvent.class));
Thread.sleep(2000L); // must sleep some time since the start up is being processed in a new thread
verify(workerNodeService, times(4)).up(CREDENTIAL_UUID, "version", "123");
assertThat(workerManager.isUp()).isTrue();
}
@Test(timeout = 5000)
public void testRunBeforeCtxClosedEvent() throws Exception {
ContextRefreshedEvent refreshEvent = mock(ContextRefreshedEvent.class);
inBuffer.onApplicationEvent(refreshEvent);
ContextClosedEvent event = mock(ContextClosedEvent.class);
when(workerManager.isUp()).thenReturn(true);
doReturn(true).when(workerStateUpdateService).isWorkerEnabled();
Thread thread = new Thread(inBuffer);
thread.start();
verify(workerManager, timeout(1000).atLeastOnce()).getInBufferSize();
inBuffer.onApplicationEvent(event);
while (thread.isAlive()) {
Thread.sleep(100L);
}
}
@Override
public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
WireMockServer wireMockServer = new WireMockServer(new WireMockConfiguration().dynamicPort());
wireMockServer.start();
configurableApplicationContext.getBeanFactory().registerSingleton("wireMockServer", wireMockServer);
configurableApplicationContext.addApplicationListener(applicationEvent -> {
if (applicationEvent instanceof ContextClosedEvent) {
wireMockServer.stop();
}
});
TestPropertyValues
.of("todo_url:http://localhost:" + wireMockServer.port() + "/todos")
.applyTo(configurableApplicationContext);
}
@Override
public void onApplicationEvent(ApplicationEvent event) {
if (event instanceof ContextRefreshedEvent
|| event instanceof ContextClosedEvent) {
if (log.isDebugEnabled()) {
log.debug("Context refreshed or closed [" + event + "]");
}
ApplicationContextEvent contextEvent = (ApplicationContextEvent) event;
ApplicationContext context = contextEvent.getApplicationContext();
BeanFactory beanFactory = context;
if (context instanceof ConfigurableApplicationContext) {
beanFactory = ((ConfigurableApplicationContext) context).getBeanFactory();
}
SleuthContextListener listener = CACHE.getOrDefault(beanFactory, this);
listener.refreshed.compareAndSet(false,
event instanceof ContextRefreshedEvent);
listener.closed.compareAndSet(false, event instanceof ContextClosedEvent);
CACHE.put(beanFactory, listener);
}
}
@Test
public void should_cancel_register_task_on_context_close() {
ApplicationRegistrator registrator = mock(ApplicationRegistrator.class);
ThreadPoolTaskScheduler scheduler = mock(ThreadPoolTaskScheduler.class);
RegistrationApplicationListener listener = new RegistrationApplicationListener(registrator, scheduler);
ScheduledFuture<?> task = mock(ScheduledFuture.class);
when(scheduler.scheduleAtFixedRate(isA(Runnable.class), eq(Duration.ofSeconds(10)))).then((invocation) -> task);
listener.onApplicationReady(new ApplicationReadyEvent(mock(SpringApplication.class), null,
mock(ConfigurableWebApplicationContext.class)));
verify(scheduler).scheduleAtFixedRate(isA(Runnable.class), eq(Duration.ofSeconds(10)));
listener.onClosedContext(new ContextClosedEvent(mock(WebApplicationContext.class)));
verify(task).cancel(true);
}
/**
* 应用程序启动过程监听
*
* @time 2018年4月10日 下午5:05:33
* @version V1.0
* @param event
*/
@Override
public void onApplicationEvent(ApplicationEvent event) {
// 在这里可以监听到Spring Boot的生命周期
if (event instanceof ApplicationEnvironmentPreparedEvent) { // 初始化环境变量
log.debug("初始化环境变量");
} else if (event instanceof ApplicationPreparedEvent) { // 初始化完成
log.debug("初始化环境变量完成");
} else if (event instanceof ContextRefreshedEvent) { // 应用刷新,当ApplicationContext初始化或者刷新时触发该事件。
log.debug("应用刷新");
} else if (event instanceof ApplicationReadyEvent) {// 应用已启动完成
log.debug("应用已启动完成");
} else if (event instanceof ContextStartedEvent) { // 应用启动,Spring2.5新增的事件,当容器调用ConfigurableApplicationContext的
// Start()方法开始/重新开始容器时触发该事件。
log.debug("应用启动");
} else if (event instanceof ContextStoppedEvent) { // 应用停止,Spring2.5新增的事件,当容器调用ConfigurableApplicationContext
// 的Stop()方法停止容器时触发该事件。
log.debug("应用停止");
} else if (event instanceof ContextClosedEvent) { // 应用关闭,当ApplicationContext被关闭时触发该事件。容器被关闭时,其管理的所有
// 单例Bean都被销毁。
log.debug("应用关闭");
} else {
}
}
@Test
public void startUpWrongVersion() throws Exception {
//shutting the service down
workerManager.onApplicationEvent(mock(ContextClosedEvent.class));
assertThat(workerManager.isUp()).isFalse();
reset(workerNodeService);
reset(engineVersionService);
when(engineVersionService.getEngineVersionId()).thenReturn("666");
//starting it again
workerManager.onApplicationEvent(mock(ContextRefreshedEvent.class));
Thread.sleep(1000L); // must sleep some time since the start up is being processed in a new thread
assertThat(workerManager.isUp()).isFalse();
reset(engineVersionService);
when(engineVersionService.getEngineVersionId()).thenReturn("123");
}
public void testBootstrapAndShutdown() throws Exception
{
// now bring up the bootstrap
ApplicationContext ctx = new ClassPathXmlApplicationContext(APP_CONTEXT_XML);
// the folder should be gone
assertFalse("Folder was not deleted by bootstrap", dir.exists());
// now create the folder again
dir.mkdir();
assertTrue("Directory not created", dir.exists());
// announce that the context is closing
ctx.publishEvent(new ContextClosedEvent(ctx));
// the folder should be gone
assertFalse("Folder was not deleted by shutdown", dir.exists());
}
@Override
public void onApplicationEvent(ApplicationContextEvent event) {
// 上下文初始化完成时启动vertx
if (event instanceof ContextRefreshedEvent) {
startHttpServer(event.getApplicationContext());
} else if (event instanceof ContextClosedEvent) {
// 上下文关闭时关闭vertx
IndexIncrementLoader loader = event.getApplicationContext().getBean(IndexIncrementLoader.class);
try {
vertx.close();
if (null != loader) {
loader.shutdown();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Test
public void shutDown() {
assertThat(workerManager.isUp()).isTrue();
reset(workerNodeService);
//shut down
workerManager.onApplicationEvent(mock(ContextClosedEvent.class));
assertThat(workerManager.isUp()).isFalse();
}
@Override
public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
final Neo4jContainer<?> neo4jContainer = new Neo4jContainer<>("neo4j:4.0").withoutAuthentication();
neo4jContainer.start();
configurableApplicationContext
.addApplicationListener((ApplicationListener<ContextClosedEvent>) event -> neo4jContainer.stop());
TestPropertyValues.of("org.neo4j.driver.uri=" + neo4jContainer.getBoltUrl())
.applyTo(configurableApplicationContext.getEnvironment());
}
@EventListener
@Order()
@Override
public void onClosedContext(ContextClosedEvent event) {
if (event.getApplicationContext().getParent() == null ||
"bootstrap".equals(event.getApplicationContext().getParent().getId())) {
stopUpdateStatus();
}
}
@EventListener
@Order()
@Override
public void onClosedContext(ContextClosedEvent event) {
if (event.getApplicationContext().getParent() == null ||
"bootstrap".equals(event.getApplicationContext().getParent().getId())) {
stopUpdateStatus();
}
}
@Test
public void testRunAfterCtxClosedEvent() throws Exception {
ContextClosedEvent event = mock(ContextClosedEvent.class);
inBuffer.onApplicationEvent(event);
inBuffer.run();
verifyZeroInteractions(queueDispatcher);
}
@Test
public void handleContextStoppedEventTest() {
processApplicationEventPublisher.setApplicationContext(publisherMock);
ContextClosedEvent contextClosedEventMock = mock(ContextClosedEvent.class);
processApplicationEventPublisher.handleContextStoppedEvent(contextClosedEventMock);
verify(publisherMock, never()).publishEvent(Mockito.any(ProcessApplicationStoppedEvent.class));
when(contextClosedEventMock.getApplicationContext()).thenReturn(publisherMock);
processApplicationEventPublisher.handleContextStoppedEvent(contextClosedEventMock);
verify(publisherMock).publishEvent(Mockito.any(ProcessApplicationStoppedEvent.class));
}
@Override
public void onApplicationEvent(ApplicationContextEvent event) {
if (event instanceof ContextRefreshedEvent && event.getApplicationContext().getParent() == null) {
startMuleContext(event.getApplicationContext());
} else if (event instanceof ContextClosedEvent) {
stopMuleContext();
}
}
@Override
public void onApplicationEvent(ContextClosedEvent event) {
try {
AppPublisher publisher = event.getApplicationContext().getBean(AppPublisher.class);
publisher.unRegister();
} catch (Exception e) {
LOGGER.info("sofa dashboard client unregister failed.", e);
}
}
@Override
public void onApplicationEvent(ContextClosedEvent event) {
System.err.println("============Close 执行=========== ");
Map<String, SocketApplication> result = event.getApplicationContext().getBeansOfType(SocketApplication.class);
for (Entry<String, SocketApplication> app : result.entrySet()) {
System.err.println(app.getKey());
app.getValue().shutdown();
}
}
@Override
public void onApplicationEvent(final ContextClosedEvent event) {
//容器停止的时候,注销当前插件加载器
if (event.getSource() == context) {
ExtensionManager.deregister(this);
}
}
@EventListener(ContextClosedEvent.class)
@Order(Ordered.HIGHEST_PRECEDENCE)
public void contextClosed(ContextClosedEvent event) throws InterruptedException {
if (isEventFromLocalContext(event)) {
updateHealthToOutOfService();
waitForKubernetesToSeeOutOfService();
}
}
@Test
public void should_not_deregister_when_not_autoDeregister() {
ApplicationRegistrator registrator = mock(ApplicationRegistrator.class);
ThreadPoolTaskScheduler scheduler = mock(ThreadPoolTaskScheduler.class);
RegistrationApplicationListener listener = new RegistrationApplicationListener(registrator, scheduler);
listener.onClosedContext(new ContextClosedEvent(mock(WebApplicationContext.class)));
verify(registrator, never()).deregister();
}
@Override
public void onApplicationEvent(ContextClosedEvent event) {
if ("true".equals(env.getProperty("radar.instance.registerSelf", "true"))) {
try {
DiscoveryClient.getInstance().deregister();
logger.info("注册退出!");
} catch (Exception e) {
logger.error("deregister_error", e);
}
}
}
@Override
public void onApplicationEvent(ContextClosedEvent event) {
try{
servCacheService.stop();
instanceTimeOutCleaner.stop();
log.info("soa客户端关闭!");
} catch (Exception e) {
log.error("soaclosederror",e);
}
}
@Override
public boolean supportsEventType(Class<? extends ApplicationEvent> eventType) {
return ApplicationPreparedEvent.class.isAssignableFrom(eventType)
|| ContextRefreshedEvent.class.isAssignableFrom(eventType)
|| ContextClosedEvent.class.isAssignableFrom(eventType);
}