java - 运行多个线程(每个线程都有自己的应用程序上下文)并正常关闭

标签 java spring multithreading spring-boot applicationcontext

我有一个多线程应用程序,正在使用 SpringBoot 1.5 重新设计。请看下面的例子:

@Service
@Lazy
class MyService {
    private static final Logger logger = LoggerFactory.getLogger(MyService.class);

    private String account;

    private boolean stopped = false;
    private boolean processing;

    public MyService(String account) {
        logger.debug("MyService constructor");
        this.account = account;
    }

    public void run() {
        logger.debug("starting thread " + account);        
        while(!stopped) {
            try {
                processing = false;
                Thread.sleep(5000); // awaiting some service response
                processing = true;
                Thread.sleep(3000); // processing service response
            } catch (InterruptedException e) {
                logger.error(null,e);
            }
        }
        logger.debug("finished gracefully");
    }

    public void stop() {
        stopped = true;
    }
}

@SpringBootApplication
public class App {

    private static final String[] accounts = { "user1", "user2", "user3" };

    public static void main(String[] args) {
        for(String account : accounts) {
            new Thread(() -> {
                ConfigurableApplicationContext context = SpringApplication.run(App.class, account);
                BeanFactory factory = context.getBeanFactory();
                MyService service = factory.getBean(MyService.class, account);

                context.addApplicationListener(event -> {
                    if(event instanceof ContextClosedEvent) {
                        service.stop();
                        // context.registerShutdownHook();
                        // context.close();
                    }
                });
                service.run();
            }).start();
        }
    }
}

应用程序属性

logging.level.com.example = DEBUG

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>multicontext-app</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.3.RELEASE</version>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
    </dependencies>

</project>

我想出了多上下文配置,因为我想 Autowiring 具有线程特定数据的“单例”作用域 bean。

问题:

  1. 这是为每个线程创建应用程序上下文的正确方法吗?
  2. 为什么我会看到重复的日志消息(线程数的平方次)?例如,当 3 个线程运行时,“MyService 构造函数”消息会打印 9 次,而不是 3 次(每个上下文一个实例)。
  3. 如何优雅地关闭每个服务线程,同时考虑到如果服务正在等待响应而不处理响应,则无需等待?目前,当应用停止时,我看不到“优雅地完成”消息。
  4. 我需要调用 context.close()context.registerShutdownHook() 还是两者都调用?我什么时候应该这样做以及如果我不这样做会发生什么?

最佳答案

有多种方法可以实现正常关闭,我将通过使用 Scheduled 技巧(我从 StackOverflow 中学到)来展示一种方法。

计划技巧在应用程序上下文启动时启动任务,但该任务永远不会再次计划(initialDelay = 0L,fixedDelay = Long.MAX_VALUE),从而有效地将计划任务转变为后台服务。 Spring 计划任务,您可以通过 SchedulingConfigurer 配置 Spring 如何处理计划任务,这使您可以控制计划任务,包括关闭。

停止正在运行的任务的正常方式是中断它们,所以我用它来停止服务。但如果确实需要,您仍然可以使用 ContextClosedEvent 来停止服务运行。

由于计划任务是异步启动的,因此不再需要在主方法中的单独线程中启动应用程序上下文。

我使用以下命令在命令行上进行了测试:
mvn clean spring-boot:run

mvn clean package spring-boot:repackage
java -jar 目标\[app].jar
按“ctrl-c”启动关闭。

@SpringBootApplication
@EnableScheduling
public class App implements SchedulingConfigurer {

    private static final Logger log = LoggerFactory.getLogger(App.class);
    private static final AtomicInteger ctxCount = new AtomicInteger();

    private static final String[] accounts = { "user1", "user2", "user3" };

    public static void main(String[] args) {

        Arrays.stream(accounts).forEach(account -> {
            ConfigurableApplicationContext context = SpringApplication.run(App.class, account);
            context.getBeanFactory().getBean(MyService.class, account);
        });
    }

    @Bean(destroyMethod="shutdown")
    public Executor taskScheduler() {
        // https://github.com/spring-projects/spring-boot/issues/7779
        final String prefix = "app-" + ctxCount.incrementAndGet() + "-mcsch-";
        log.debug("Creating task scheduler {}", prefix);
        ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
        scheduler.setPoolSize(1);
        scheduler.setThreadNamePrefix(prefix);
        scheduler.setWaitForTasksToCompleteOnShutdown(true);
        scheduler.setAwaitTerminationSeconds(20);
        return scheduler;
    }

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        log.debug("Setting task scheduler.");
        taskRegistrar.setScheduler(taskScheduler());
    }

    @Service
    @Lazy
    static class MyService {

        private String account;

        public MyService(String account) {
            log.debug("{} - MyService constructor", account);
            this.account = account;
        }

        // trick to "run at startup"
        @Scheduled(initialDelay = 0L, fixedDelay = Long.MAX_VALUE)
        public void run() {
            boolean stopped = false;
            while(!stopped) {
                try {
                    log.debug("{} - sleeping", account);        
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    log.debug("{} - sleep interrupted", account);
                    stopped = true;
                }
            }
            log.debug("{} - finished gracefully", account);
        }
    } // MyService

}

关于java - 运行多个线程(每个线程都有自己的应用程序上下文)并正常关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43321414/

相关文章:

java - 在这种情况下,ConcurrentHashMap 和 Synchronized Hash Map 哪个更好?

multithreading - 线程池和多核系统

java - java数据结构异常

java - 如何改变JProgressbar的 "string painted"的颜色?

Java将int值转换为char

spring - 从 Controller 运行 Spring 批处理作业

Spring WS : Why is Spring WS returning WebServiceTransportException instead of a SoapFaultException

java - jsoup 提取标签中元素的值

java - Spring JDBCtemplate ROWMapper 太慢

c# - 线程在 WPF 应用程序中抛出 System.OutOfMemoryException