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

jopen 11年前

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

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

下载,安装和配置Redis

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" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"            p:hostName="localhost" p:port="6379" p:usePool="true">      </bean>        <!-- redis template definition -->      <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"            p:connectionFactory-ref="redisConnectionFactory"/>        <bean id="redisDAO" class="net.dredis.dao.impl.RedisDAOImpl">          <property name="redisTemplate" ref="redisTemplate" />      </bean>        <bean id="listener" class="net.dredis.listener.impl.MessageDelegateListenerImpl"/>        <!-- the default ConnectionFactory -->      <bean id="jdkSerializer" class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />        <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" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"            p:hostName="localhost" p:port="6379" p:usePool="true">      </bean>        <!-- redis template definition -->      <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"            p:connectionFactory-ref="jedisConnectionFactory"/>        <bean id="redisDAO" class="net.dredis.dao.impl.RedisDAOImpl">          <property name="redisTemplate" ref="redisTemplate" />      </bean>     <bean id="serialization" class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />     <bean id="messageDelegateListener" class="net.dredis.listener.impl.MessageDelegateListenerImpl" />         <bean id="messageListener" class="org.springframework.data.redis.listener.adapter.MessageListenerAdapter">          <property name="delegate" ref="messageDelegateListener" />          <property name="serializer" ref="serialization" />      </bean>        <bean id="redisContainer" class="org.springframework.data.redis.listener.RedisMessageListenerContainer">          <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 class="org.springframework.data.redis.listener.ChannelTopic">                          <constructor-arg value="java" />                      </bean>                  </entry>              </map>          </property>      </bean>  </beans>
</div> </div> </div>