我有一個多線程應用程序,我正在使用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();
}
}
}
application.properties
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>
我想出了多情境配置,因爲我想自動裝配 「單身」具有線程特定數據的範圍化bean。
問題:
- 它是一個正確的方式來創建每個線程應用程序上下文?
- 爲什麼我可以看到重複的日誌消息(線程數平方時間)?例如,當3個線程正在運行時,「MyService構造函數」消息被打印9次,而不是3次(每個上下文有一個實例)。
- 如何正常關閉每個服務線程,考慮到如果服務正在等待響應而不處理它,則不需要等待?目前,當應用程序停止時,我看不到「完成優雅」的消息。
- 我需要撥打
context.close()
或context.registerShutdownHook()
或兩者嗎?當我應該這樣做時,會發生什麼事情,我不會那樣做?
我想知道,stateful ful單身豆的用例是什麼?這是我之前從未在Spring引導中遇到過的模式,只是好奇而已。 –
HttpClient保持身份驗證令牌有一些生命週期?或者多次驗證會更好?多少個bean的實例被創建? – gumkins