|
Redis是一个key-value的存储系统,提供的key-value类似与Memcached而数据结构又多于memcached,而且性能优异.广泛用于缓存,临时存储等.而我今天 这个例子是使用Redis实现一个订阅/发布系统,而不是如何使用它存储key-value的数据.
Redis是天生支持订阅/发布的,不是我牵强附会拼凑而实现这样的效果,如果真是这样性能没法保证,而且要实现订阅/发布这样的系统是有很多解决方案的.
下载,安装和配置Redis,见: http://my.oschina.net/u/729474/blog/79128 和http://www.php100.com/html/webkaifa/PHP/PHPyingyong/2011/0406/7873.html
Spring一直秉承不发明轮子的,对于很多其他技术都是提供一个模板:Template,如JDBC-JdbcTemplate,JMSTemplate等,Redis他也提供RedisTemplate,有了这个RedisTemplate你可以做任何事,存取key-value,订阅,发布等都通过这个对象实现.
实现一个RedisDAO,接口我不贴了
01 | public class RedisDAOImpl implements RedisDAO { |
03 | private RedisTemplate<String, Object> redisTemplate = null; |
05 | public RedisDAOImpl() { |
10 | public void sendMessage(String channel, Serializable message) { |
11 | redisTemplate.convertAndSend(channel, message); |
15 | public RedisTemplate getRedisTemplate() { |
19 | public void setRedisTemplate(RedisTemplate redisTemplate) { |
20 | this.redisTemplate = redisTemplate; |
可以看到,通过这个 sendMessage方法,我可以把一条可序列化的消息发送到channel频道,订阅者只要订阅了这个channel,他就会接收发布者发布的消息.
当然有了发布消息的sendMessage也得有个接收消息的Listener,用于接收订阅到的消息.
代码如:
01 | public class MessageDelegateListenerImpl implements MessageDelegateListener { |
04 | public void handleMessage(Serializable message) { |
07 | System.out.println("null"); |
08 | } else if(message.getClass().isArray()){ |
09 | System.out.println(Arrays.toString((Object[])message)); |
10 | } else if(message instanceof List<?>) { |
11 | System.out.println(message); |
12 | } else if(message instanceof Map<? , ?>) { |
13 | System.out.println(message); |
15 | System.out.println(ToStringBuilder.reflectionToString(message)); |
好了,有上面的两个类,加上Spring基本上就可以工作了.当然还得启动Redis.
Spring Schema:01 | <?xml version="1.0" encoding="UTF-8"?> |
02 | <beans xmlns="http://www.springframework.org/schema/beans" |
03 | xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" |
04 | xmlns:context="http://www.springframework.org/schema/context" |
05 | xmlns:redis="http://www.springframework.org/schema/redis" |
06 | xmlns:p="http://www.springframework.org/schema/p" |
08 | xsi:schemaLocation="http://www.springframework.org/schema/beans |
09 | http://www.springframework.org/schema/beans/spring-beans-3.0.xsd |
10 | http://www.springframework.org/schema/context |
11 | http://www.springframework.org/schema/context/spring-context-3.0.xsd |
12 | http://www.springframework.org/schema/redis |
13 | http://www.springframework.org/schema/redis/spring-redis-1.0.xsd"> |
[table=98%,initial][tr][td]15[/td][td] |
|
|