1.springboot使用多线程任务时bean 不能使用@Autowired注入 可以提供一个外部类去获取bean对象
@Component
public class ApplicationProvider implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
/**
* 获取applicationContext
*
* @return
*/
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
public static Object getBean(String name){
return applicationContext.getBean(name);
}
public static <T> T getBean(Class beanclass){
return (T)applicationContext.getBean(beanclass);
}
public static <T> T getBean(String name, Class<T> clazz) {
return applicationContext.getBean(name, clazz);
}
2.在多线程类执行任务时
ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.submit(() -> {
// 使用ApplicationProvider.getBean 方法去获取对应的servicebean对象
IndexDao3 bean1 = ApplicationProvider.getBean(IndexDao3.class);
bean1.query();
});
3.在如上线程操作完成时可以在Controller层定义一个全局变量以便接收数据,当第一次请求可以使用一个全局boolean变量进行锁住(相当于轻量级锁)当线程把值返回时在把全局boolean变量置为原始值。
具体使用方式见如下:
public static Object test;
Test.test = bean1.query();
if (ReportController.bool) {
if (ReportController.yearReportri == null) {
return ReportController.yearReportri;
} else {
ReportController.bool = false;
return ReportController.yearReportri;
}
} else {
ReportController.yearReportri = null;
ReportController.bool = true;
ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.execute(() -> {
ReportController.yearReportri = ApplicationContextProvider.getBean(ReportController.class).yearReport(bean);
});
executorService.shutdown();
}
当然也可以使用redis去存数据使用key value形式