整个demo步骤如下:
(1)由于项目是maven项目,需配置pom.xml下载jedis和dwr。如果是普通的web项目,自行下载jar包
<!-- jedis -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.8.0</version>
</dependency>
<!-- dwr -->
<dependency>
<groupId>org.directwebremoting</groupId>
<artifactId>dwr</artifactId>
<version>3.0.2-RELEASE</version>
</dependency>
(2)配置web.xml
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1" metadata-complete="true">
<!-- 如果是用mvn命令生成的xml,需要修改servlet版本为3.1 -->
<!-- 配置DispatcherServlet -->
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.js</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.css</url-pattern>
</servlet-mapping>
<!-- DWR服务器推技术 -->
<servlet>
<servlet-name>dwr-invoker</servlet-name>
<servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class>
<init-param>
<param-name >org.directwebremoting.extend.ScriptSessionManager </param-name>
<param-value >com.demo1.dwr.DWRScriptSessionManager </param-value>
</init-param>
<init-param>
<param-name>debug</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<!-- comet方式 -->
<param-name>activeReverseAjaxEnabled</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>crossDomainSessionSecurity</param-name>
<param-value>false</param-value>
</init-param>
<init-param>
<param-name>allowScriptTagRemoting</param-name>
<param-value>true</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>dwr-invoker</servlet-name>
<url-pattern>/dwr/*</url-pattern>
</servlet-mapping>
</web-app>
(3)新建一个dwr.xml,必须与web,xml在同一级目录下,其中value是对应的java类,稍后在后边会有代码
<!DOCTYPE dwr PUBLIC
"-//GetAhead Limited//DTD Direct Web Remoting 3.0//EN"
"http://getahead.org/dwr/dwr30.dtd">
<dwr>
<allow>
<create creator="new" javascript="MessagePush">
<param name="class" value="com.demo1.dwr.MessagePush" />
</create>
<create creator="new" javascript="JedisPubSubMessage">
<param name="class" value="com.demo1.jedis.JedisPubSubMessage" />
</create>
</allow>
</dwr>
(4)MessagePush类,在这个类中,改成自己要连的jedis服务器
package com.demo1.dwr;
import javax.servlet.ServletException;
import org.directwebremoting.ScriptSession;
import org.directwebremoting.WebContextFactory;
import com.demo1.jedis.JedisPubSubMessage1;
import redis.clients.jedis.Jedis;
public class MessagePush{
//订阅频道
public void subTest(final String channel){
final Jedis jedis=new Jedis("172.16.239.10",6379);
jedis.auth("wxh");
ScriptSession scriptsession =WebContextFactory.get().getScriptSession();
scriptsession.setAttribute("sub","true");
scriptsession.setAttribute("subname",channel);
final JedisPubSubMessage1 jsm = new JedisPubSubMessage1();
// jedis.subscribe(jsm, channel);
Thread t= new Thread(new Runnable(){
public void run(){
jedis.subscribe(jsm, channel);
}
});
t.start();
}
//发布消息
public void pubTest(String channel,String message){
Jedis jedis=new Jedis("172.16.239.10",6379);
jedis.auth("wxh");
jedis.publish(channel, message);
}
}
(5) jedisPubSubMessage
package com.demo1.jedis;
import java.util.Collection;
import org.directwebremoting.Browser;
import org.directwebremoting.ScriptBuffer;
import org.directwebremoting.ScriptSession;
import org.directwebremoting.ScriptSessionFilter;
import org.directwebremoting.ScriptSessions;
import org.directwebremoting.ServerContextFactory;
import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;
import com.demo1.dwr.DWRScriptSessionListener;
import redis.clients.jedis.JedisPubSub;
/**
* *******消息订阅处理类*******
* @author Administrator
*
*/
public class JedisPubSubMessage extends JedisPubSub {
// 监听到订阅频道接受到消息时的回调 (onMessage )
@Override
public void onMessage(String channel, String message) {
//接收订阅频道消息后,业务处理逻辑
//super.onMessage(channel, message);
//System.out.println("通道为: "+channel+" "+"监听意见被通知,收到的消息为:"+message);
final String Msg=message;
final String cha=channel;
System.out.println("channel是:"+cha);
Browser.withAllSessionsFiltered(new ScriptSessionFilter() {
public boolean match(ScriptSession session) {
if(("true").equals(session.getAttribute("sub"))&&(cha.equals(session.getAttribute("subname")))){
//if(session.getAttribute("sub")=="true"){
return true;
}
return false;
}
}, new Runnable(){
private ScriptBuffer script = new ScriptBuffer();
public void run(){
//推送消息
script.appendCall("showMsg",Msg);
//得到所有ScriptSession
Collection<ScriptSession> sessions = Browser.getTargetSessions();
//Collection<ScriptSession> sessions = DWRScriptSessionListener.getScriptSessions();
for (ScriptSession scriptSession : sessions){
System.out.println("接收消息成功");
//添加待执行的脚本到dwr excution池中
scriptSession.addScript(script);
}
}
});
}
// 订阅频道模式时的回调 ( onPSubscribe )
@Override
public void onSubscribe(String channel, int subscribedChannels) {
// TODO Auto-generated method stub
//super.onSubscribe(channel, subscribedChannels);
System.out.println(" >> 开始订阅 频道,订阅的频道为: "+channel);
final String chan=channel;
Browser.withAllSessionsFiltered(new ScriptSessionFilter() {
public boolean match(ScriptSession session) {
if(("true").equals(session.getAttribute("sub"))){
return true;
}else{
return false;
}
}
}, new Runnable(){
private ScriptBuffer script = new ScriptBuffer();
public void run(){
//推送消息
script.appendCall("showchan",chan);
//得到所有ScriptSession
Collection<ScriptSession> sessions = Browser.getTargetSessions();
for (ScriptSession scriptSession : sessions){
System.out.println("订阅频道成功");
//添加待执行的脚本到dwr excution池中
scriptSession.addScript(script);
}
}
});
}
}
(6)新建一个dwrsub.jsp,此页面主要实现订阅功能。
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<base href="<%=basePath%>">
</head>
<script type='text/javascript' src='dwr/engine.js'></script>
<script type='text/javascript' src='dwr/util.js'></script>
<script type="text/javascript" src="dwr/interface/MessagePush.js"></script>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="dwr/interface/JedisPubSubMessage.js"></script>
<script type="text/javascript" src="dwr/interface/JedisPubSubMessage1.js"></script>
<script type="text/javascript">
function showMsg(Msg){
alert("消息接收成功");
$("#msg").val(Msg);
}
/* function test1() {
JedisPubSubMessage.onMessage("ss","ss1");
} */
function sub(){
var cha=$("#channe").val();
MessagePush.subTest(cha);
}
function showchan(chan){
alert("订阅成功");
}
</script>
<body onload="dwr.engine.setActiveReverseAjax(true);dwr.engine.setNotifyServerOnPageUnload(true);;">
频道: <input type="text" id="channe" >
<input type="button" onclick="sub()" value="订阅"><br/>
频道收到到的消息: <input type="text" id="msg">
</body>
</html>
注意:
//这个方法用来启动该页面的ReverseAjax功能
dwr.engine.setActiveReverseAjax( true);
//设置在页面关闭时,通知服务端销毁会话
dwr.engine.setNotifyServerOnPageUnload( true);
(7)新建一个dwrpub.jsp,此页面主要实现发布功能
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<base href="<%=basePath%>">
</head>
<script type='text/javascript' src='dwr/engine.js'></script>
<script type='text/javascript' src='dwr/util.js'></script>
<script type="text/javascript" src="dwr/interface/MessagePush.js"></script>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="dwr/interface/JedisPubSubMessage.js"></script>
<script type="text/javascript" src="dwr/interface/JedisPubSubMessage1.js"></script>
<script type="text/javascript">
function pub(){
var ch=$("#chan1").val()
var ms=$("#message").val();
MessagePush.pubTest(ch,ms);
}
/* function showchan(chan){
alert("频道接收成功");
$("#chan1").val(chan);
} */
</script>
<body onload="dwr.engine.setActiveReverseAjax(true);dwr.engine.setNotifyServerOnPageUnload(true);;">
<!-- <body> -->
频道: <input type="text" id="chan1">
消息: <input type="text" id="message" >
<input type="button" onclick="pub()" value="发布">
</body>
</html>
完成这几步,访问这两个页面就能实现dwr+发布订阅的功能了。注意在运行此代码时,记得启动redis服务器。