前言
Redis不仅可作为缓存服务器,还可用作消息队列。它的列表类型天生支持用作消息队列。如下图所示:
1.导入包
implementation group: 'redis.clients', name: 'jedis', version: '2.9.0'
2.填写配置信息
spring:
redis:
host: xxx
port: xxx
password: xxx
timeout: 10000
3.配置监听适配器
@Configuration
public class RedisConfig {
@Bean
RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
MessageListenerAdapter listenerAdapter) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
//订阅通道
//这个container 可以添加多个 messageListener 监听多个通道
container.addMessageListener(listenerAdapter, new PatternTopic("Notice"));
return container;
}
@Bean
MessageListenerAdapter listenerAdapter(RedisService redisSendService) {
return new MessageListenerAdapter(redisSendService, "onMessage");
}
}
4.消费消息
@Service
public class RedisService implements MessageListener {
@Override
public void onMessage(Message message, byte[] pattern) {
try {
System.out.println("收到消息:"+message.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
5.发布消息
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class RedisServiceTest {
@Autowired
private StringRedisTemplate redisTemplate;
@Test
public void redisSend() {
redisTemplate.convertAndSend("Notice", "在知识的海洋里狗刨!!!");
}
}