springboot前端长轮询使用多线程异步执行任务

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形式

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值