Spring MVC how to get progress of running async task

后端 未结 4 893
轻奢々
轻奢々 2020-12-30 10:09

I would like to start an asynchronous task from within controller like in following code sniplet from Spring docs.

import org.springframework.core.task.Tas         


        
4条回答
  •  臣服心动
    2020-12-30 10:48

    Have you looked at the @Async annotation in the Spring reference doc?

    First, create a bean for your asynchronous task:

    @Service
    public class AsyncServiceBean implements ServiceBean {
    
        private AtomicInteger cn;
    
        @Async
        public void doSomething() { 
            // triggers the async task, which updates the cn status accordingly
        }
    
        public Integer getCn() {
            return cn.get();
        }
    }
    

    Next, call it from the controller:

    @Controller
    public class YourController {
    
        private final ServiceBean bean;
    
        @Autowired
        YourController(ServiceBean bean) {
            this.bean = bean;
        }
    
        @RequestMapping(value = "/trigger")
        void triggerAsyncJob() {
            bean.doSomething();
        }
    
        @RequestMapping(value = "/status")
        @ResponseBody
        Map fetchStatus() {
            return Collections.singletonMap("cn", bean.getCn());
        }        
    }
    

    Remember to configure an executor accordingly, e.g.

    
    
    

提交回复
热议问题