因此,我试图通过将Java代码迁移到Spring Boot来学习Spring Boot。
我有一部分Java代码,如下所示:
int threadLimit = 5, interval = 2;
ScheduledExecutorService ses = Executors.newScheduledThreadPool(threadLimit);
for (int i = 0; i < executionThreadLimit; i++) {
WorkerThread worker = new WorkerThread("WorkerThread");
ses.scheduleAtFixedRate(worker, 0, interval, TimeUnit.SECONDS);
}
此处WorkerThread
实现了Runnable
;
上述代码的相应Spring Boot替代方法:
自定义池类:
@Configuration
public class Test {
@Bean
public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
threadPoolTaskScheduler.setPoolSize(5);
threadPoolTaskScheduler.setThreadNamePrefix("ThreadPoolTaskScheduler");
return threadPoolTaskScheduler;
}
}
WorkerThread类:
@Component
@Scope("prototype")
public class WorkerThread implements Runnable {
private Logger logger = LogManager.getLogger(this.getClass().getName());
private String threadName = null;
@Autowired
private AppParameter app;
@Override
public void run() {
logger.info("Thread :: " + this + " is running -- > " + app.getA() + " && " + app.getB());
}
}
测试类:
@Component
public class TestCommandLineRunner implements CommandLineRunner {
private final Logger logger = LogManager.getLogger(this.getClass().getName());
@Autowired
private ThreadPoolTaskScheduler taskScheduler;
@Override
public void run(String... args) throws Exception {
int threadLimit = 5, interval = 2000; // these 2 are dynamic values but provided statically for testing purposes
for(int i = 0; i< threadLimit; i++) {
WorkerThread wt = new WorkerThread();
taskScheduler.scheduleAtFixedRate(wt, interval);
}
}
}
现在这是我的问题所在。如果我需要启动5个WorkerThread
实例,则必须做WorkerThread wt = new WorkerThread();
,但是如果这样做,则WorkerThread
将不再是Spring托管的bean。
所以我的问题是如何创建线程类为Spring Managed Bean的线程池?
我只是开始使用Spring Boot,因此有人会介意帮助我吗?谢谢。
我已经参考了以下文档, https://www.baeldung.com/spring-task-scheduler https://mkyong.com/spring/spring-and-java-thread-example/ 但无法提出可行的解决方案。
答案 0 :(得分:0)
您可以使用ObjectFactory
@Autowired
private ThreadPoolTaskScheduler taskScheduler;
@Autowired
private ObjectFactory<WorkerThread> threadFactory;
@Override
public void run(String... args) throws Exception {
int threadLimit = 5, interval = 2000; // these 2 are dynamic values but provided statically for testing purposes
for(int i = 0; i< threadLimit; i++) {
WorkerThread wt = threadFactory.getObject();
taskScheduler.scheduleAtFixedRate(wt, interval);
}
}