Redis中pub/sub特性,可以用来实现类似与JMS的“topic”功能,只不过这些消息无法被持久化而已。spring-data-redis组件中对pub/sub提供了类似JMS的编程模式,我们通过实例来展示如何使用。
需要注意的是,在redis中消息的订阅端(subscribe)需要独占链接,那么消息接收将是阻塞的。
代码实例中,使用了“连接池”/“消息异步接受”“消息并发处理”,请根据需要调整相关参数。
1) Redis中"pub/sub"的消息,为"即发即失",server不会保存消息,如果publish的消息,没有任何client处于"subscribe"状态,消息将会被丢弃.如果client在subcribe时,链接断开后重连,那么此期间的消息也将丢失.Redis server将会"尽力"将消息发送给处于subscribe状态的client,但是仍不会保证每条消息都能被正确接收.
2) 如果期望pub/sub的消息时持久的,那么需要借助额外的功能.参见"pub/sub持久化订阅"
一.配置文件:
- "http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd" default-autowire="byName">
- "jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
- "maxActive" value="32">
- "maxIdle" value="6">
- "maxWait" value="15000">
- "minEvictableIdleTimeMillis" value="300000">
- "numTestsPerEvictionRun" value="3">
- "timeBetweenEvictionRunsMillis" value="60000">
- "whenExhaustedAction" value="1">
-
- "jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" destroy-method="destroy">
- "poolConfig" ref="jedisPoolConfig">
- "hostName" value="127.0.0.1">
- "port" value="6379">
- "password" value="0123456">
- "timeout" value="15000">
- "usePool" value="true">
-
- "jedisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
- "connectionFactory" ref="jedisConnectionFactory">
- "defaultSerializer">
- class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
-
-
-
- "topicMessageListener" class="com.sample.redis.sdr.TopicMessageListener">
- "redisTemplate" ref="jedisTemplate">
-
- "topicContainer" class="org.springframework.data.redis.listener.RedisMessageListenerContainer" destroy-method="destroy">
- "connectionFactory" ref="jedisConnectionFactory"/>
- "taskExecutor">
- class="org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler">
- "poolSize" value="3">
-
-
- "messageListeners">
-
- "topicMessageListener">
- class="org.springframework.data.redis.listener.ChannelTopic">
- "user:topic"/>
-
-
-
-
-
-
二.消息发布(pub):
- String channel = "user:topic";
-
-
-
-
- redisTemplate.convertAndSend(channel, "from app 1");
三.消息接收(subscribe):
1) TopicMessageListener类:
- public class TopicMessageListener implements MessageListener {
-
- private RedisTemplate redisTemplate;
-
- public void setRedisTemplate(RedisTemplate redisTemplate) {
- this.redisTemplate = redisTemplate;
- }
-
- @Override
- public void onMessage(Message message, byte[] pattern) {
- byte[] body = message.getBody();
- byte[] channel = message.getChannel();
-
-
- String itemValue = (String)redisTemplate.getValueSerializer().deserialize(body);
- String topic = (String)redisTemplate.getStringSerializer().deserialize(channel);
-
- }
- }
2) 你会发现上述编程风格非常像JMS。需要注意的是消息体的反序列化。