当前位置:网站首页>Using undertow, Nacos offline logout delay after service stop
Using undertow, Nacos offline logout delay after service stop
2022-07-26 10:14:00 【Whale-52 Hz】
Use undertow, After the service stops nacos Logoff delay
The overall problem is to use gateway As a gateway , After the service goes offline . The gateway will still forward to the offline server . This article solves the problem at the end of the service , Another article :spring cloud gateway+nacos Service offline perception delay , The request is still forwarded to the offline service It solves the problem of gateway .
1. Scene description
It's not clear whether it's the version problem or the configuration . Just record this problem .
nacos client :1.4.1
web The server :undertow edition 2.2.3.Final
After the service stops ,nacos The management side view service did not log off in time .
web The server is switched to tomcat, Service offline and normal logout .
Probably because nacos One required to perform logout bean It has been destroyed first . Causes logout to fail . The console has an error message
2022-04-25 11:48:39.431 ERROR 21336 --- [extShutdownHook] c.a.cloud.nacos.discovery.NacosWatch : namingService unsubscribe failed, properties:NacosDiscoveryProperties{serverAddr='localhost:8848', endpoint='', namespace='dong-dev', watchDelay=30000, logName='', service='dong-sys-server-biz', weight=1.0, clusterName='DEFAULT', group='DEFAULT_GROUP', namingLoadCacheAtStart='false', metadata={dubbo.metadata-service.urls=[ "dubbo://10.47.17.177:20880/com.alibaba.cloud.dubbo.service.DubboMetadataService?anyhost=true&application=dong-sys-server-biz&bind.ip=10.47.17.177&bind.port=20880&deprecated=false&dubbo=2.0.2&dynamic=true&generic=false&group=dong-sys-server-biz&interface=com.alibaba.cloud.dubbo.service.DubboMetadataService&methods=getAllServiceKeys,getServiceRestMetadata,getExportedURLs,getAllExportedURLs&pid=21336&qos.enable=false&release=2.7.14&revision=2.2.7.RELEASE&service.name=ServiceBean:dong-sys-server-biz/com.alibaba.cloud.dubbo.service.DubboMetadataService:1.0.0&side=provider&timeout=13000×tamp=1650858511190&version=1.0.0" ], dubbo.metadata.revision=0, preserved.register.source=SPRING_CLOUD, S-Version=10.47.17.177}, registerEnabled=true, ip='10.47.17.177', networkInterface='', port=8082, secure=false, accessKey='', secretKey='', heartBeatInterval=null, heartBeatTimeout=null, ipDeleteTimeout=null}
java.lang.NullPointerException: null
at io.undertow.servlet.spec.ServletContextImpl.getInitParameterNames(ServletContextImpl.java:430) ~[undertow-servlet-2.2.3.Final.jar:2.2.3.Final]
at org.springframework.web.context.support.ServletContextPropertySource.getPropertyNames(ServletContextPropertySource.java:41) ~[spring-web-5.3.3.jar:5.3.3]
at com.alibaba.spring.util.PropertySourcesUtils.getPropertyNames(PropertySourcesUtils.java:130) ~[spring-context-support-1.0.11.jar:na]
at com.alibaba.spring.util.PropertySourcesUtils.getSubProperties(PropertySourcesUtils.java:103) ~[spring-context-support-1.0.11.jar:na]
at com.alibaba.spring.util.PropertySourcesUtils.getSubProperties(PropertySourcesUtils.java:57) ~[spring-context-support-1.0.11.jar:na]
at com.alibaba.cloud.nacos.NacosDiscoveryProperties.enrichNacosDiscoveryProperties(NacosDiscoveryProperties.java:616) ~[spring-cloud-starter-alibaba-nacos-discovery-2021.1.jar:2021.1]
at com.alibaba.cloud.nacos.NacosDiscoveryProperties.getNacosProperties(NacosDiscoveryProperties.java:610) ~[spring-cloud-starter-alibaba-nacos-discovery-2021.1.jar:2021.1]
at com.alibaba.cloud.nacos.discovery.NacosWatch.stop(NacosWatch.java:165) [spring-cloud-starter-alibaba-nacos-discovery-2021.1.jar:2021.1]
at com.alibaba.cloud.nacos.discovery.NacosWatch.stop(NacosWatch.java:97) [spring-cloud-starter-alibaba-nacos-discovery-2021.1.jar:2021.1]
at org.springframework.context.support.DefaultLifecycleProcessor.doStop(DefaultLifecycleProcessor.java:234) [spring-context-5.3.3.jar:5.3.3]
at org.springframework.context.support.DefaultLifecycleProcessor.access$300(DefaultLifecycleProcessor.java:54) [spring-context-5.3.3.jar:5.3.3]
at org.springframework.context.support.DefaultLifecycleProcessor$LifecycleGroup.stop(DefaultLifecycleProcessor.java:373) [spring-context-5.3.3.jar:5.3.3]
at org.springframework.context.support.DefaultLifecycleProcessor.stopBeans(DefaultLifecycleProcessor.java:206) [spring-context-5.3.3.jar:5.3.3]
at org.springframework.context.support.DefaultLifecycleProcessor.onClose(DefaultLifecycleProcessor.java:129) [spring-context-5.3.3.jar:5.3.3]
at org.springframework.context.support.AbstractApplicationContext.doClose(AbstractApplicationContext.java:1072) [spring-context-5.3.3.jar:5.3.3]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.doClose(ServletWebServerApplicationContext.java:171) [spring-boot-2.4.2.jar:2.4.2]
at org.springframework.context.support.AbstractApplicationContext$1.run(AbstractApplicationContext.java:996) [spring-context-5.3.3.jar:5.3.3]
2. Solution
2.1web The server is switched to tomcat
Direct replacement , Problem solving
2.2 Make your own cancellation compensation
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.commons.util.InetUtils;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
/** * nacos Registry compensation * * perform org.springframework.cloud.client.serviceregistry.AbstractAutoServiceRegistration#destroy() Before destruction , * Probably org.springframework.boot.web.embedded.undertow.UndertowWebServer#stop() Has been executed . * Lead to io.undertow.servlet.spec.ServletContextImpl#getInitParameterNames happen NPE, Therefore, it is impossible to get offline from the Registration Center . * * @Author: dong * @Date: 2021/12/24 15:24 */
@Slf4j
@Component
public class SelfNacosDiscovery {
@Value("${spring.cloud.nacos.discovery.namespace:public}")
private String namespaceId;
private String clusterName = "DEFAULT";
@Value("${spring.application.name:}")
private String serviceName;
@Value("${server.port:8080}")
private String port;
@Value("${spring.cloud.nacos.discovery.server-addr:}")
private String nacosAddr;
@Autowired
private InetUtils inetUtils;
/** * Compensation cancellation * com.alibaba.nacos.client.naming.net.NamingProxy#deregisterService(java.lang.String, com.alibaba.nacos.api.naming.pojo.Instance) *@Author dong *@Date 2021/12/24 15:58 *@param *@return */
public void deregisterService(){
HttpResponse execute = null;
try{
if(StrUtil.isAllNotBlank(namespaceId,serviceName,port,nacosAddr)){
String name = "[email protected]@"+serviceName;
String ipAddress = inetUtils.findFirstNonLoopbackHostInfo().getIpAddress();
Map<String, Object> params = new HashMap<String, Object>(8);
params.put("namespaceId", namespaceId);
params.put("serviceName", name);
params.put("clusterName", clusterName);
// com.alibaba.cloud.nacos.NacosDiscoveryProperties.init
params.put("ip", ipAddress);
params.put("port", port);
params.put("ephemeral", "true");
log.info("nacos Compensation cancellation process : Actuator information namespaceId={},serviceName={},clusterName={},ip={},port={}",namespaceId,
name,clusterName,ipAddress,port);
HttpRequest request = HttpUtil.createRequest(Method.DELETE, nacosAddr + "/nacos/v1/ns/instance");
execute = request.form(params).execute();
log.info("nacos Compensation cancellation process results :{}",execute.body());
}else{
log.warn("nacos The compensation cancellation process is not implemented : Incomplete parameters !");
}
}catch (Exception e){
log.error("nacos Compensation cancellation process abnormal ",e);
}finally {
if(execute!=null){
execute.close();
}
}
}
}
2.3 Use nacos Built in logout ( recommend )
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.serviceregistry.AbstractAutoServiceRegistration;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
@Slf4j
@Component
public class SelfNacosDiscovery {
@Resource
private AbstractAutoServiceRegistration abstractAutoServiceRegistration;
@EventListener(ContextClosedEvent.class)
public void doDeregister() {
log.info("nacos Compensation cancellation process , Start ");
try {
abstractAutoServiceRegistration.destroy();
}catch (Exception e){
}
log.info("nacos Compensation cancellation process , end ");
}
}
20220609 to update
2.3 When the service is stopped, an exception will be printed . as follows :
org.springframework.beans.factory.BeanCreationNotAllowedException: Error creating bean with name 'selfNacosDiscovery': Singleton bean creation not allowed while singletons of this factory are in destruction (Do not request a bean from a BeanFactory in a destroy method implementation!)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton
....
SelfNacosDiscovery Just a little modification :
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.serviceregistry.AbstractAutoServiceRegistration;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
@Slf4j
@Component
public class SelfNacosDiscovery implements ApplicationListener<ContextClosedEvent>{
@Resource
private AbstractAutoServiceRegistration abstractAutoServiceRegistration;
@EventListener(ContextClosedEvent.class)
public void doDeregister() {
log.info("nacos Compensation cancellation process , Start ");
try {
abstractAutoServiceRegistration.destroy();
}catch (Exception e){
}
log.info("nacos Compensation cancellation process , end ");
}
@Override
public void onApplicationEvent(ContextClosedEvent event) {
doDeregister();
}
}
边栏推荐
- AirTest
- Wechat applet learning notes 2
- 时间序列异常检测
- Principle analysis and source code interpretation of service discovery
- What is the principle of reflection mechanism?
- 在.NET 6.0中配置WebHostBuilder
- SSG framework Gatsby accesses the database and displays it on the page
- Okaleido生态核心权益OKA,尽在聚变Mining模式
- 点赞,《新程序员》电子书限时免费领啦!
- Server memory failure prediction can actually do this!
猜你喜欢

Apple dominates, Samsung revives, and domestic mobile phones fail in the high-end market

SQL优化的魅力!从 30248s 到 0.001s

AR model in MATLAB for short-term traffic flow prediction

数通基础-二层交换原理

Beginner of flask framework-04-flask blueprint and code separation

服务发现原理分析与源码解读

Solve proxyerror: CONDA cannot proceed due to an error in your proxy configuration

Mysql5.7.25 master-slave replication (one-way)

Basics of data communication - basic knowledge of network
![[datawhale] [machine learning] Diabetes genetic risk detection challenge](/img/98/7981af7948feb73168e5200b3dfac9.png)
[datawhale] [machine learning] Diabetes genetic risk detection challenge
随机推荐
[MySQL database] a collection of basic MySQL operations - the basis of seeing (adding, deleting, modifying, and querying)
Learning about opencv (3)
解释一下自动装箱和自动拆箱?
Node memory overflow and V8 garbage collection mechanism
Jpg to EPS
Docker configuring MySQL Cluster
Nodejs service background execution (forever)
Azkaban [basic knowledge 01] core concepts + features +web interface + Architecture +job type (you can get started with Azkaban workflow scheduling system in one article)
反射机制的原理是什么?
Installation and use of cocoapods
云原生(三十六) | Kubernetes篇之Harbor入门和安装
Matlab Simulink realizes fuzzy PID control of time-delay temperature control system of central air conditioning
Introduction to latex, EPS picture bounding box
Mqtt x cli officially released: powerful and easy-to-use mqtt 5.0 command line tool
Unstoppable, pure domestic PCs have been in place, and the monopoly of the U.S. software and hardware system has been officially broken
2022 zhongkepan cloud - server internal information acquisition and analysis flag
Under win10 64 bit, matlab fails to configure notebook
Tableviewcell highly adaptive
Production of a-modal drag function in antui
Replay the snake game with C language (II) end