Spring Data Redis实现一个订阅/发布系统

来源:互联网 发布:阿尔法营创意编程 编辑:程序博客网 时间:2024/06/07 22:59

Redis是一个key-value的存储系统,提供的key-value类似与Memcached而数据结构又多于memcached,而且性能优异.广泛用于缓存,临时存储等.而我今天 这个例子是使用Redis实现一个订阅/发布系统,而不是如何使用它存储key-value的数据.

Redis是天生支持订阅/发布的,不是我牵强附会拼凑而实现这样的效果,如果真是这样性能没法保证,而且要实现订阅/发布这样的系统是有很多解决方案的.

下载,安装和配置Redis,见:

  1. http://www.linuxidc.com/Linux/2012-10/73081.htm
  2. http://www.linuxidc.com/Linux/2012-10/73082.htm
  3. http://www.linuxidc.com/Linux/2012-10/73080.htm
  4. http://www.linuxidc.com/Linux/2012-10/73078.htm
  5. http://www.linuxidc.com/Linux/2012-10/73079.htm

Spring一直秉承不发明轮子的,对于很多其他技术都是提供一个模板:Template,如JDBC-JdbcTemplate,JMSTemplate等,Redis他也提供RedisTemplate,有了这个RedisTemplate你可以做任何事,存取key-value,订阅,发布等都通过这个对象实现.

实现一个RedisDAO,接口我不贴了

public class RedisDAOImpl implements RedisDAO {

private RedisTemplate<String, Object> redisTemplate = null;

public RedisDAOImpl() {

}

@Override
public void sendMessage(String channel, Serializable message) {
redisTemplate.convertAndSend(channel, message);
}
public RedisTemplate getRedisTemplate() {
return redisTemplate;
}

public void setRedisTemplate(RedisTemplate redisTemplate) {
this.redisTemplate = redisTemplate;
}
}

可以看到,通过这个 sendMessage方法,我可以把一条可序列化的消息发送到channel频道,订阅者只要订阅了这个channel,他就会接收发布者发布的消息.

当然有了发布消息的sendMessage也得有个接收消息的Listener,用于接收订阅到的消息.

代码如:

public class MessageDelegateListenerImpl implements MessageDelegateListener {

@Override
public void handleMessage(Serializable message) {
//什么都不做,只输出
if(message == null){
System.out.println(“null”);
} else if(message.getClass().isArray()){
System.out.println(Arrays.toString((Object[])message));
} else if(message instanceof List<?>) {
System.out.println(message);
} else if(message instanceof Map<? , ?>) {
System.out.println(message);
} else {
System.out.println(ToStringBuilder.reflectionToString(message));
}
}
}

好了,有上面的两个类,加上Spring基本上就可以工作了.当然还得启动Redis.
Spring Schema:

<?xml version=”1.0″ encoding=”UTF-8″?>
<beans xmlns=”http://www.springframework.org/schema/beans”
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
xmlns:context=”http://www.springframework.org/schema/context”
xmlns:redis=”http://www.springframework.org/schema/redis”
xmlns:p=”http://www.springframework.org/schema/p”

xsi:schemaLocation=”http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context-3.0.xsd

http://www.springframework.org/schema/redis

http://www.springframework.org/schema/redis/spring-redis-1.0.xsd”>

<bean id=”redisConnectionFactory”
p:hostName=”localhost” p:port=”6379″ p:usePool=”true”>
</bean>

<!– redis template definition –>
<bean id=”redisTemplate”
p:connectionFactory-ref=”redisConnectionFactory”/>

<bean id=”redisDAO”>
<property name=”redisTemplate” ref=”redisTemplate” />
</bean>

<bean id=”listener”/>

<!– the default ConnectionFactory –>
<bean id=”jdkSerializer” />

<redis:listener-container>
<!– the method attribute can be skipped as the default method name is “handleMessage” –>
<redis:listener ref=”listener” serializer=”jdkSerializer” method=”handleMessage” topic=”java” />
</redis:listener-container>
</beans>

如上面的配置, jdkSerializer是jdk默认的序列化的实现,当然还有很多其他序列化Java对象的方法,这里使用jdk默认实现.

Method属性是配置订阅系统接收消息的方法,默认也是”handleMessage”

topic就是订阅的channel频道,是有发布到java这个channel的消息才会被接收.

测试类:

public static void main(String[] args) {
new ClassPathXmlApplicationContext(“pubsubAppContext1.xml”);;
while (true) { //这里是一个死循环,目的就是让进程不退出,用于接收发布的消息
try {
System.out.println(“current time: ” + new Date());

Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

OK,启动了订阅系统后,我们就可以发布消息,测试类如:

@Test
public void testPublishMessage() throws Exception {
String msg = “Hello, Redis!”;
redisDAO.sendMessage(“java”, msg); //发布字符串消息
RedisTestBean bean = new RedisTestBean(“123456″);
bean.setName(“ZhenQin”);
bean.setOld((byte)23);
bean.setSeliry((short)4000);
bean.setManbers(new String[]{“234567″, “3456789″});
redisDAO.sendMessage(“java”, bean); //发布一个普通的javabean消息
Integer[] values = new Integer[]{21341,123123,12323};
redisDAO.sendMessage(“java”, values);  //发布一个数组消息
}

如测试,我连续发布了3条消息,都是不同的数据类型.订阅端输出如:

current time: Fri Oct 26 20:38:31 CST 2012
[21341, 123123, 12323]
java.lang.String@379faa8c[value={H,e,l,l,o,,, ,R,e,d,i,s,!},hash=1345989452]
net.dredis.entity.RedisTestBean@7dee05dc[uid=123456,name=ZhenQin,seliry=4000,old=23,manbers={234567,3456789}]
current time: Fri Oct 26 20:38:34 CST 2012
current time: Fri Oct 26 20:38:37 CST 2012

OK他接收到了这3条消息,而且和预期一样.
对于Spring还有传统风格的配置方式,实现的功能和前面一模一样.

<?xml version=”1.0″ encoding=”UTF-8″?>
<beans xmlns=”http://www.springframework.org/schema/beans”
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
xmlns:context=”http://www.springframework.org/schema/context”
xmlns:p=”http://www.springframework.org/schema/p”

xsi:schemaLocation=”http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd“>

<bean id=”jedisConnectionFactory”
p:hostName=”localhost” p:port=”6379″ p:usePool=”true”>
</bean>

<!– redis template definition –>
<bean id=”redisTemplate”
p:connectionFactory-ref=”jedisConnectionFactory”/>

<bean id=”redisDAO”>
<property name=”redisTemplate” ref=”redisTemplate” />
</bean>

<bean id=”serialization” />

<bean id=”messageDelegateListener” />

<bean id=”messageListener”>
<property name=”delegate” ref=”messageDelegateListener” />
<property name=”serializer” ref=”serialization” />
</bean>

<bean id=”redisContainer”>
<property name=”connectionFactory” ref=”jedisConnectionFactory”/>
<property name=”messageListeners”>
<!– map of listeners and their associated topics (channels or/and patterns) –>
<map>
<entry key-ref=”messageListener”>
<bean>
<constructor-arg value=”java” />
</bean>
</entry>
</map>
</property>
</bean>
</beans>


参考:http://www.open-open.com/lib/view/open1351324403395.html

0 0