服务端推送技术之——Servlet 3.0+异步方法处理

一 开启异步方式支持

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration.Dynamic;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

public class WebInitializer implements WebApplicationInitializer {//1

    @Override
    public void onStartup(ServletContext servletContext)
            throws ServletException {
        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
        ctx.register(MyMvcConfig.class);
        ctx.setServletContext(servletContext); //2
        
        Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx)); //3
        servlet.addMapping("/");
        servlet.setLoadOnStartup(1);
        servlet.setAsyncSupported(true);//开启异步方法支持

    }

}

二 控制器

package com.wisely.highlight_springmvc4.web.ch4_5;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.async.DeferredResult;

import com.wisely.highlight_springmvc4.service.PushService;

@Controller
public class AysncController {
    @Autowired
    PushService pushService; //定时任务,定时更新DeferredResult

    @RequestMapping("/defer")
    @ResponseBody
    //返回给客户端DeferredResult
    public DeferredResult<String> deferredCall() { 
        //异步任务的实现是通过控制器从另外一个线程返回一个DeferredResult,这里的DeferredResult
        //是从pushService中获得的。
        return pushService.getAsyncUpdate();
    }

}

三 定时任务

package com.wisely.highlight_springmvc4.service;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.async.DeferredResult;

@Service
public class PushService {
    //在PushService里产生DeferredResult给控制器使用
    private DeferredResult<String> deferredResult; 

    public DeferredResult<String> getAsyncUpdate() {
        deferredResult = new DeferredResult<String>();
        return deferredResult;
    }

    //通过Scheduled注解的方法定时更新DeferredResult
    @Scheduled(fixedDelay = 5000)
    public void refresh() {
        if (deferredResult != null) {
            deferredResult.setResult(new Long(System.currentTimeMillis())
                    .toString());
        }
    }


}

四 演示页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>servlet async support</title>
</head>
<body>
<script type="text/javascript" src="assets/js/jquery.js"></script>
<script type="text/javascript">
       deferred();//页面打开就向后台发送请求
       
       function deferred(){
           $.get('defer',function(data){
               console.log(data); //在控制台输出服务端推送的数据
               deferred(); //一次请求完成后再向后台发送请求
           });
       }
</script>
</body>
</html>

五 配置

@Configuration
@EnableWebMvc
@EnableScheduling  //开启计划任务
@ComponentScan("com.wisely.highlight_springmvc4")
public class MyMvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        //添加页面映射关系
        registry.addViewController("/async").setViewName("/async");
    }
}

六 测试

1 浏览器输入http://localhost:8080/highlight_springmvc4/async

2 控制台输出

猜你喜欢

转载自blog.csdn.net/chengqiuming/article/details/81809306