AJAX长轮询的方法来解决频繁对后台的请求,进一步减小压力
在实现过程发现AJAX的多次请求会出现多线程并发的问题又使用线程同步来解决该问题
个人对ajax长轮询的一点愚见
ajax请示后台时,后台程序并没有立即返回信息而是挂起,当符合条件时才会返回信息
从ajax定时请求变成轮询模式:
function getRtmMsg(show){
$.ajax({
type:"POST",
url:"rtmAction!getMsg.action",
data:"show="+show,
success: function(msg){
if(msg!=null){
bottomRight();
getRtmMsg("0");
}
}
});
}
后台代码:
/**
* 实时消息Action
* @author wangwei
* May 23, 2013
*/
public class RtmAction extends ActionSupport{
HttpServletResponse response = ServletActionContext.getResponse();
HttpServletRequest request = ServletActionContext.getRequest();
private static final ThreadLocal threadLocal = new ThreadLocal();
private static Object lock = new Object();
public void getMsg(){
String show = request.getParameter("show");
if("0".equals(show)){
RtmTemplate.cjzxShow = false;
}
try {
//多线程同步解决并发问题
synchronized(lock){
while(!RtmTemplate.cjzxShow){
System.out.println("检测中。。。。");
Thread.sleep(5000);
}
}
response.getWriter().println("1");
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}