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;
    }

}
相关文章
相关标签/搜索