javaWeb項目中需要一個實時提醒的功能,也就是某人做了某一操作,可以立即提醒到當前在線的用戶
最開始想在用戶做了操作後,儲存一個狀態到數據庫中然後用每隔幾秒用ajax去請求後臺查詢數據庫來確定是否顯示提醒窗口
提醒窗口使用jquery easyui 的messager 在右下角彈出如下圖
後查得可通過AJAX長輪詢的方法來解決頻繁對後臺的請求,進一步減小壓力
在實現過程發現AJAX的多次請求會出現多線程併發的問題又使用線程同步來解決該問題
個人對ajax長輪詢的一點愚見
ajax請示後臺時,後臺程序並沒有立即返回信息而是掛起,當符合條件時纔會返回信息
文筆不好,只能白話出來,如有不對的地方還請各位指正,一起探討學習!
現貼出部分代碼
js ajax實現部分
function getRtmMsg(show){
$.ajax({
type:"POST",
url:"rtmAction!getMsg.action",
data:"show="+show,
success: function(msg){
if(msg!=null){
bottomRight();
getRtmMsg("0");
}
}
});
}
使用 jquery easyui的messager彈出提示窗口代碼
function bottomRight(){
$.messager.show({
title:'提醒',
msg:'下載考生',
showType:'show'
});
}
後臺Action
/**
* 實時消息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();
}
}
}