Spring Cloud 框架优雅关机和重启
共 6845字,需浏览 14分钟
·
2023-07-10 06:31
背景
我们编写的Web项目部署之后,经常会因为需要进行配置变更或功能迭代而重启服务,单纯的kill -9 pid
的方式会强制关闭进程,这样就会导致服务端当前正在处理的请求失败,那有没有更优雅的方式来实现关机或重启呢?
在项目正常运行的过程中,如果直接不加限制的重启可能会发生一下问题
-
项目重启(关闭)时,调用方可能会请求到已经停掉的项目,导致拒绝连接错误(503),调用方服务会缓存一些服务列表导致,服务列表依然还有已经关闭的项目实例信息
-
项目本身存在一部分任务需要处理,强行关闭导致这部分数据丢失,比如内存队列、线程队列、MQ 关闭导致重复消费
为了解决上面出现的问题,提供以下解决方案:
-
关于问题 1 采用将需要重启的项目实例,提前 40s 从 nacos 上剔除,然后再重启对应的项目,保证有 40s 的时间可以用来服务发现刷新实例信息,防止调用方将请求发送到该项目
-
使用 Spring Boot 提供的优雅停机选项,再次预留一部分时间
-
使用 shutdonwhook 完成自定的关闭操作
该方案主要考虑因为服务下线的瞬间,如果 Nacos 服务剔除不及时,导致仍有部分请求转发到该服务的情况
在项目增加一个接口,同时在准备关停项目前执行 stop 方法,先主动剔除这个服务,shell 改动如下:
run.sh
function stop()
{
echo "Stop service please waiting...."
echo "deregister."
curl -X POST "127.0.0.1:${SERVER_PORT}/discovery/deregister"
echo ""
echo "deregister [${PROJECT}] then sleep 40 seconds."
# 这里 sleep 40 秒,因为 Nacos 默认的拉取新实例的时间为 30s, 如果调用方不修改的化,这里应该最短为 30s
# 考虑到已经接收的请求还需要一定的时间进行处理,这里预留 10s, 如果 10s 还没处理完预留的请求,调用方肯定也超时了
# 所以这里是 30 + 10 = 40sleep 40
kill -s SIGTERM ${PID}
if [ $? -eq 0 ];then
echo "Stop service done."
else
echo "Stop service failed!"
fi
}
在项目中增加 /discovery/deregister
接口
Spring Boot MVC 版本
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.serviceregistry.Registration;
import org.springframework.cloud.client.serviceregistry.ServiceRegistry;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@SuppressWarnings("SpringJavaAutowiredFieldsWarningInspection")
@RestController
@RequestMapping("discovery")
@Slf4j
public class DeregisterInstanceController {
@Autowired
@Lazy
private ServiceRegistry serviceRegistry;
@Autowired
@Lazy
private Registration registration;
@PostMapping("deregister")
public ResultVO<String> deregister() {
log.info("deregister serviceName:{}, ip:{}, port:{}",
registration.getServiceId(),
registration.getHost(),
registration.getPort());
try {
serviceRegistry.deregister(registration);
} catch (Exception e) {
log.error("deregister from nacos error", e);
return ResultVO.failure(e.getMessage());
}
return ResultVO.success();
}
}
Spring Cloud Gateway
通过使用 GatewayFilter
方式来处理
package com.br.zeus.gateway.filter;
import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.isAlreadyRouted;
import com.alibaba.fastjson.JSON;
import com.br.zeus.gateway.entity.RulesResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.serviceregistry.Registration;
import org.springframework.cloud.client.serviceregistry.ServiceRegistry;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
@SuppressWarnings("SpringJavaAutowiredFieldsWarningInspection")
@Component
@Slf4j
public class DeregisterInstanceGatewayFilter implements GatewayFilter, Ordered {
@Autowired
@Lazy
private ServiceRegistry serviceRegistry;
@Autowired
@Lazy
private Registration registration;
public DeregisterInstanceGatewayFilter() {
log.info("DeregisterInstanceGatewayFilter 启用");
}
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
if (isAlreadyRouted(exchange)) {
return chain.filter(exchange);
}
log.info("deregister serviceName:{}, ip:{}, port:{}",
registration.getServiceId(),
registration.getHost(),
registration.getPort());
RulesResult result = new RulesResult();
try {
serviceRegistry.deregister(registration);
result.setSuccess(true);
} catch (Exception e) {
log.error("deregister from nacos error", e);
result.setSuccess(false);
result.setMessage(e.getMessage());
}
ServerHttpResponse response = exchange.getResponse();
response.getHeaders().setContentType(MediaType.APPLICATION_JSON_UTF8);
DataBuffer bodyDataBuffer = response.bufferFactory().wrap(JSON.toJSONBytes(result));
response.setStatusCode(HttpStatus.OK);
return response.writeWith(Mono.just(bodyDataBuffer));
}
@Override
public int getOrder() {
return 0;
}
}
在路由配置时,增加接口和过滤器的关系
.route("DeregisterInstance", r -> r.path("/discovery/deregister")
.filters(f -> f.filter(deregisterInstanceGatewayFilter))
.uri("https://example.com"))
二、Spring Boot 自带的优雅停机方案
要求 Spring Boot 的版本大于等于 2.3
在配置文件中增加如下配置:
application.yaml
server:
shutdown: graceful
spring:
lifecycle:
timeout-per-shutdown-phase: 10s
当使用 server.shutdown=graceful
启用时,在 web 容器关闭时,web 服务器将不再接收新请求,并将等待活动请求完成的缓冲期。使用 timeout-per-shutdown-phase
配置最长等待时间,超过该时间后关闭
public class MyShutdownHook {
public static void main(String[] args) {
// 创建一个新线程作为ShutdownHook
Thread shutdownHook = new Thread(() -> {
System.out.println("ShutdownHook is running...");
// 执行清理操作或其他必要的任务
// 1. 关闭 MQ
// 2. 关闭线程池
// 3. 保存一些数据
});
// 注册ShutdownHook
Runtime.getRuntime().addShutdownHook(shutdownHook);
// 其他程序逻辑
System.out.println("Main program is running...");
// 模拟程序执行
try {
Thread.sleep(5000); // 假设程序运行5秒钟
} catch (InterruptedException e) {
e.printStackTrace();
}
// 当程序退出时,ShutdownHook将被触发执行
}
}