fix(print): stop NacosWatch and drain traffic before Undertow context shutdown

This commit is contained in:
tsiji 2026-11-18 16:49:00 +08:00
parent 6c0fac5e46
commit 023483f1ba
2 changed files with 186 additions and 0 deletions

View File

@ -0,0 +1,63 @@
package com.foreverwin.nlv.print.config;
import com.alibaba.cloud.nacos.discovery.NacosWatch;
import com.alibaba.cloud.nacos.registry.NacosAutoServiceRegistration;
import com.alibaba.cloud.nacos.registry.NacosRegistration;
import com.alibaba.cloud.nacos.registry.NacosServiceRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.stereotype.Component;
@Component
public class NacosWatchShutdown implements ApplicationListener<ContextClosedEvent> {
private static final Logger log = LoggerFactory.getLogger(NacosWatchShutdown.class);
private final ApplicationContext context;
private final ObjectProvider<NacosWatch> watches;
private final ObjectProvider<NacosAutoServiceRegistration> registrations;
private final ObjectProvider<NacosRegistration> instances;
private final ObjectProvider<NacosServiceRegistry> registries;
private final long drainSeconds;
public NacosWatchShutdown(ApplicationContext context, ObjectProvider<NacosWatch> watches,
ObjectProvider<NacosAutoServiceRegistration> registrations,
ObjectProvider<NacosRegistration> instances, ObjectProvider<NacosServiceRegistry> registries,
@Value("${app.shutdown.drain-seconds:0}") long drainSeconds) {
this.context = context;
this.watches = watches;
this.registrations = registrations;
this.instances = instances;
this.registries = registries;
this.drainSeconds = drainSeconds;
}
@Override
public void onApplicationEvent(ContextClosedEvent event) {
if (event.getApplicationContext() == context) {
// Unsubscribe while the servlet property sources are still accessible.
watches.ifAvailable(NacosWatch::stop);
NacosRegistration instance = instances.getIfAvailable();
NacosServiceRegistry registry = registries.getIfAvailable();
if (instance != null && registry != null) {
// Keep the naming client open for in-flight HTTP requests while callers
// expire their cached instance lists.
registry.deregister(instance);
if (drainSeconds > 0) {
log.info("Nacos drain started for {} seconds", drainSeconds);
try {
Thread.sleep(drainSeconds * 1000L);
} catch (InterruptedException interrupted) {
Thread.currentThread().interrupt();
}
log.info("Nacos drain completed");
}
}
// Close the naming client only after cached callers have drained.
registrations.ifAvailable(NacosAutoServiceRegistration::stop);
}
}
}

View File

@ -0,0 +1,123 @@
package com.foreverwin.nlv.print.config;
import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.NacosServiceManager;
import com.alibaba.cloud.nacos.discovery.NacosWatch;
import com.alibaba.cloud.nacos.registry.NacosAutoServiceRegistration;
import com.alibaba.cloud.nacos.registry.NacosRegistration;
import com.alibaba.cloud.nacos.registry.NacosServiceRegistry;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.listener.EventListener;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.support.StaticListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.SmartLifecycle;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.core.env.MapPropertySource;
import org.springframework.test.util.ReflectionTestUtils;
import java.util.Collections;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
class NacosWatchShutdownTest {
@Test
void unsubscribesBeforeWebServerDestroysServletPropertySources() throws Exception {
GenericApplicationContext context = new GenericApplicationContext();
AtomicBoolean destroyed = new AtomicBoolean();
context.getEnvironment().getPropertySources().addFirst(new MapPropertySource("servlet", Collections.emptyMap()) {
@Override
public String[] getPropertyNames() {
if (destroyed.get()) throw new IllegalStateException("UT015023: This Context has been already destroyed");
return super.getPropertyNames();
}
});
NacosDiscoveryProperties properties = new NacosDiscoveryProperties();
properties.setServerAddr("127.0.0.1:8848");
properties.setNamespace("");
properties.setEndpoint("");
properties.setLogName("");
properties.setAccessKey("");
properties.setSecretKey("");
properties.setService("nlv-print");
properties.setGroup("DEFAULT_GROUP");
properties.setClusterName("DEFAULT");
ReflectionTestUtils.setField(properties, "environment", context.getEnvironment());
NacosServiceManager manager = mock(NacosServiceManager.class);
NamingService naming = mock(NamingService.class);
when(manager.getNamingService(any(Properties.class))).thenReturn(naming);
NacosWatch watch = new NacosWatch(manager, properties);
context.registerBean("nacosWatch", NacosWatch.class, () -> watch);
NacosAutoServiceRegistration registration = mock(NacosAutoServiceRegistration.class);
NacosRegistration instance = mock(NacosRegistration.class);
NacosServiceRegistry registry = mock(NacosServiceRegistry.class);
AtomicLong deregisteredAt = new AtomicLong();
doAnswer(call -> {
assertFalse(destroyed.get(), "Deregister while HTTP can still serve cached clients");
deregisteredAt.set(System.nanoTime());
return null;
}).when(registry).deregister(instance);
doAnswer(call -> {
assertFalse(destroyed.get());
assertTrue(System.nanoTime() - deregisteredAt.get() >= 900_000_000L,
"Keep the naming client open throughout the configured drain");
return null;
}).when(registration).stop();
context.registerBean(NacosRegistration.class, () -> instance);
context.registerBean(NacosServiceRegistry.class, () -> registry);
context.registerBean(NacosAutoServiceRegistration.class, () -> registration);
context.registerBean(NacosWatchShutdown.class,
() -> new NacosWatchShutdown(context, context.getBeanFactory().getBeanProvider(NacosWatch.class),
context.getBeanFactory().getBeanProvider(NacosAutoServiceRegistration.class),
context.getBeanFactory().getBeanProvider(NacosRegistration.class),
context.getBeanFactory().getBeanProvider(NacosServiceRegistry.class), 1));
context.registerBean("webServer", SmartLifecycle.class, () -> new SmartLifecycle() {
private boolean running;
public void start() { running = true; }
public void stop() { destroyed.set(true); running = false; }
public boolean isRunning() { return running; }
public int getPhase() { return Integer.MAX_VALUE; }
});
try {
context.refresh();
assertTrue(watch.isRunning());
} finally {
context.close();
}
assertTrue(destroyed.get());
assertFalse(watch.isRunning());
verify(registration, atLeastOnce()).stop();
verify(naming).unsubscribe(eq("nlv-print"), eq("DEFAULT_GROUP"),
eq(Collections.singletonList("DEFAULT")), any(EventListener.class));
}
@Test
void ignoresChildContextClosureAndAllowsDisabledWatch() {
ApplicationContext owner = mock(ApplicationContext.class);
NacosWatch watch = mock(NacosWatch.class);
StaticListableBeanFactory beans = new StaticListableBeanFactory();
beans.addBean("watch", watch);
NacosAutoServiceRegistration registration = mock(NacosAutoServiceRegistration.class);
beans.addBean("registration", registration);
NacosWatchShutdown listener = new NacosWatchShutdown(owner, beans.getBeanProvider(NacosWatch.class),
beans.getBeanProvider(NacosAutoServiceRegistration.class),
beans.getBeanProvider(NacosRegistration.class), beans.getBeanProvider(NacosServiceRegistry.class), 0);
listener.onApplicationEvent(new ContextClosedEvent(mock(ApplicationContext.class)));
verify(watch, never()).stop();
verify(registration, never()).stop();
listener.onApplicationEvent(new ContextClosedEvent(owner));
verify(watch).stop();
verify(registration).stop();
StaticListableBeanFactory empty = new StaticListableBeanFactory();
assertDoesNotThrow(() -> new NacosWatchShutdown(owner, empty.getBeanProvider(NacosWatch.class),
empty.getBeanProvider(NacosAutoServiceRegistration.class),
empty.getBeanProvider(NacosRegistration.class), empty.getBeanProvider(NacosServiceRegistry.class), 0)
.onApplicationEvent(new ContextClosedEvent(owner)));
}
}