spring mvc異步操做處理,註解方式

簡單的異步操做處理;本用例使用的spring mvc框架,進行異步處理web

首先設置web.xml:將是否支持異步設置爲truespring

<servlet>
   <servlet-name>SpringMVC</servlet-name>
   <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
   <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring-mvc.xml</param-value>
   </init-param>
   <load-on-startup>1</load-on-startup>
   <!--是否支持異步-->
   <async-supported>true</async-supported>
</servlet>

spring-mvc.xmlspring-mvc

<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
   xmlns:context="http://www.springframework.org/schema/context"
   xmlns:mvc="http://www.springframework.org/schema/mvc"
   xmlns:task="http://www.springframework.org/schema/task"
   xsi:schemaLocation="http://www.springframework.org/schema/beans  
                        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd  
                        http://www.springframework.org/schema/context  
                        http://www.springframework.org/schema/context/spring-context-3.1.xsd  
                        http://www.springframework.org/schema/mvc  
                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
                  http://www.springframework.org/schema/task
                      http://www.springframework.org/schema/task/spring-task-3.2.xsd">
<!-- 支持異步方法執行 -->
<task:executor id="task_executor" pool-size="5"/>
<task:annotation-driven executor="task_executor"/>

service業務邏輯:mvc

public interface ITaskService {
    @Async
    void asyncDemo();
}
@Service
@EnableAsync
public class TaskServiceImpl implements ITaskService {

    @Async
    @Override
    public void asyncDemo() {
        try {
            System.out.println("異步執行開始:"+new Date());
            Thread.sleep(10 * 1000);
            System.out.println("異步執行完畢:"+new Date());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

controller調用:app

@Controller
@RequestMapping("/asyncTestDemo")
public class AsyncTestDemo {
    @Autowired
    private ITaskService taskService;

    @RequestMapping(params = "async")
    @ResponseBody
    public Map async(HttpServletRequest request) {
        Map map = new HashMap();
        map.put("code","201");
        taskService.asyncDemo();
        map.put("code","200");
        return map;
    }

}
相關文章
相關標籤/搜索