前面针对graceful shutdown写了两篇文章
第一篇:
https://blog.youkuaiyun.com/chenshm/article/details/139640775
只考虑了阻塞线程,没有考虑异步线程
第二篇:
https://blog.youkuaiyun.com/chenshm/article/details/139702105
第二篇考虑了多线程的安全性,包括异步线程。
1. 为什么还需要优化呢?
因为第二篇的写法还不够优美,它存在以下缺陷。
- 只在一个service bean 里面对ExecutorService做predestroy,只能对一个service类的异步线程提供安全保障,其他service类的异步业务需要重写predestroy的逻辑,造成代码冗余。
- 异步方法的写法比较麻烦,其他程序员并不常用。现在用springboot的程序员喜欢用@Async注解,随时随地可以把方法变成异步执行。
从架构师的角度考虑的话,写代码尽量满足多数情况可用,易用,最好还是全局有效的,让其他程序员专注于写业务代码。
接下来让我们实现@Async注解的异步方法在app graceful shutdow时保持线程安全。
2. 代码优化
-
确认graceful shutdown settings
-
添加第一个servcie 的异步方法
package com.it.sandwich.service.impl;
import com.it.sandwich.service.Demo2Service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
/**
* @Author 公众号: IT三明治
* @Date 2024/6/16
* @Description:
*/
@Slf4j
@Service
@Component
public class Demo2ServiceImpl implements Demo2Service {
@Override
@Async
public void feedUserInfoToOtherService(String userId) throws InterruptedException {
for (int i = 0; i < 40; i++) {
log.info("Demo2Service update {} login info to other services, service num: {}", userId, i+1);
Thread