当前位置:网站首页>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();
}
}
边栏推荐
- Interview shock 68: why does TCP need three handshakes?
- Sqoop【环境搭建 01】CentOS Linux release 7.5 安装配置 sqoop-1.4.7 解决警告并验证(附Sqoop1+Sqoop2最新版安装包+MySQL驱动包资源)
- Principle analysis and source code interpretation of service discovery
- 如何写一篇百万阅读量的文章
- 汉诺塔II|汉诺塔4柱
- Learning about opencv (1)
- Data communication foundation - layer 2 switching principle
- Use of pclint in vs2013
- JS table auto cycle scrolling, mouse move in pause
- regular expression
猜你喜欢

新增市场竞争激烈,中国移动被迫推出限制性超低价5G套餐

The practice of OpenCV -- bank card number recognition

Map key not configured and uniapp routing configuration and jump are reported by the uniapp < map >< /map > component

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

Meeting OA project (III) -- my meeting (meeting seating and submission for approval)

Uni app learning summary

Okaleido ecological core equity Oka, all in fusion mining mode

Matlab Simulink realizes fuzzy PID control of time-delay temperature control system of central air conditioning
![[qualcomm][network] QTI service analysis](/img/76/49054ff8c7215eca98cc479ab1d986.png)
[qualcomm][network] QTI service analysis

30 minutes to thoroughly understand the synchronized lock upgrade process
随机推荐
Sqoop [put it into practice 02] sqoop latest version full database import + data filtering + field type support description and example code (query parameter and field type forced conversion)
Usage of the formatter attribute of El table
Meeting OA project (III) -- my meeting (meeting seating and submission for approval)
Mqtt x cli officially released: powerful and easy-to-use mqtt 5.0 command line tool
Strange Towers of Hanoi|汉诺塔4柱问题
Sqoop【付诸实践 02】Sqoop1最新版 全库导入 + 数据过滤 + 字段类型支持 说明及举例代码(query参数及字段类型强制转换)
数通基础-STP原理
Data communication foundation - layer 2 switching principle
Principle analysis and source code interpretation of service discovery
Reproduce the snake game in C language (I) build pages and construct snakes
Flask framework beginner-03-template
[information system project manager] summary of essence of high-level series for the first time
如何写一篇百万阅读量的文章
In Net 6.0
Set view dynamic picture
PHP executes shell script
Vs Code configures go locale and successfully installs go related plug-ins in vscode problem: Tools failed to install
Interpretation of the standard of software programming level examination for teenagers_ second level
Study notes at the end of summer vacation
Interview shock 68: why does TCP need three handshakes?