- 在线文档
- 项目结构
1.源码克隆:git clone https://github.com/spring-guides/gs-messaging-redis.git 2.包含两个项目initial和complete,initial可以根据文档练习完善,complete是完整项目 3.功能描述:构建应用程序,使用 Spring Data Redis 发布和订阅通过 Redis 发送的消息 4.Redis安装:https://blog.csdn.net/tongxin_tongmeng/article/details/127491655
-
源码分析
1.POM依赖 <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies>
2.入口类 // https://blog.csdn.net/tongxin_tongmeng/article/details/128401278 @SpringBootApplication public class MessagingRedisApplication { private static final Logger LOGGER = LoggerFactory.getLogger(MessagingRedisApplication.class); @Bean RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory, MessageListenerAdapter listenerAdapter) { RedisMessageListenerContainer container = new RedisMessageListenerContainer(); container.setConnectionFactory(connectionFactory); container.addMessageListener(listenerAdapter, new PatternTopic("chat")); return container; } @Bean MessageListenerAdapter listenerAdapter(Receiver receiver) { return new MessageListenerAdapter(receiver, "receiveMessage"); } @Bean Receiver receiver() { return new Receiver(); } @Bean StringRedisTemplate template(RedisConnectionFactory connectionFactory) { return new StringRedisTemplate(connectionFactory); } public static void main(String[] args) throws InterruptedException { ApplicationContext ctx = SpringApplication.run(MessagingRedisApplication.class, args); StringRedisTemplate template = ctx.getBean(StringRedisTemplate.class); Receiver receiver = ctx.getBean(Receiver.class); while (receiver.getCount() == 0) { LOGGER.info("Sending message..."); template.convertAndSend("chat", "Hello from Redis!"); Thread.sleep(500L); } System.exit(0); } }
3.发送消息 public static void main(String[] args) throws InterruptedException { ApplicationContext ctx = SpringApplication.run(MessagingRedisApplication.class, args); StringRedisTemplate template = ctx.getBean(StringRedisTemplate.class); Receiver receiver = ctx.getBean(Receiver.class); while (receiver.getCount() == 0) { LOGGER.info("Sending message..."); template.convertAndSend("chat", "Hello from Redis!"); Thread.sleep(500L); } System.exit(0); }
4.接收消息 public class Receiver { private static final Logger LOGGER = LoggerFactory.getLogger(Receiver.class); private AtomicInteger counter = new AtomicInteger(); public void receiveMessage(String message) { LOGGER.info("Received <" + message + ">"); counter.incrementAndGet(); } public int getCount() { return counter.get(); } }
- 项目演示