Spring Boot文档阅读笔记-Messaging with Redis

﹏ヽ暗。殇╰゛Y 2023-01-05 12:22 263阅读 0赞

首先要启动Redis服务端

  1. redis-server

redis启动后会有如下信息:

  1. [35142] 01 May 14:36:28.939 # Warning: no config file specified, using the default config. In order to specify a config file use redis-server /path/to/redis.conf
  2. [35142] 01 May 14:36:28.940 * Max number of open files set to 10032
  3. _._
  4. _.-``__ ''-._
  5. _.-`` `. `_. ''-._ Redis 2.6.12 (00000000/0) 64 bit
  6. .-`` .-```. ```\/ _.,_ ''-._
  7. ( ' , .-` | `, ) Running in stand alone mode
  8. |`-._`-...-` __...-.``-._|'` _.-'| Port: 6379
  9. | `-._ `._ / _.-' | PID: 35142
  10. `-._ `-._ `-./ _.-' _.-'
  11. |`-._`-._ `-.__.-' _.-'_.-'|
  12. | `-._`-._ _.-'_.-' | https://redis.io
  13. `-._ `-._`-.__.-'_.-' _.-'
  14. |`-._`-._ `-.__.-' _.-'_.-'|
  15. | `-._`-._ _.-'_.-' |
  16. `-._ `-._`-.__.-'_.-' _.-'
  17. `-._ `-.__.-' _.-'
  18. `-._ _.-'
  19. `-.__.-'
  20. [35142] 01 May 14:36:28.941 # Server started, Redis version 2.6.12
  21. [35142] 01 May 14:36:28.941 * The server is now ready to accept connections on port 6379

Maven配置如下:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <parent>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-parent</artifactId>
  8. <version>2.4.1</version>
  9. <relativePath/> <!-- lookup parent from repository -->
  10. </parent>
  11. <groupId>cn.it1995</groupId>
  12. <artifactId>demo</artifactId>
  13. <version>0.0.1-SNAPSHOT</version>
  14. <name>demo</name>
  15. <description>Demo project for Spring Boot</description>
  16. <properties>
  17. <java.version>1.8</java.version>
  18. </properties>
  19. <dependencies>
  20. <dependency>
  21. <groupId>org.springframework.boot</groupId>
  22. <artifactId>spring-boot-starter-data-redis</artifactId>
  23. </dependency>
  24. <dependency>
  25. <groupId>org.springframework.boot</groupId>
  26. <artifactId>spring-boot-starter-web</artifactId>
  27. </dependency>
  28. <dependency>
  29. <groupId>org.projectlombok</groupId>
  30. <artifactId>lombok</artifactId>
  31. <optional>true</optional>
  32. </dependency>
  33. <dependency>
  34. <groupId>org.springframework.boot</groupId>
  35. <artifactId>spring-boot-starter-test</artifactId>
  36. <scope>test</scope>
  37. </dependency>
  38. </dependencies>
  39. <build>
  40. <plugins>
  41. <plugin>
  42. <groupId>org.springframework.boot</groupId>
  43. <artifactId>spring-boot-maven-plugin</artifactId>
  44. <configuration>
  45. <excludes>
  46. <exclude>
  47. <groupId>org.projectlombok</groupId>
  48. <artifactId>lombok</artifactId>
  49. </exclude>
  50. </excludes>
  51. </configuration>
  52. </plugin>
  53. </plugins>
  54. </build>
  55. </project>

创建Redis消息接受者

发布者发送消息,然后接受者接收消息,下面是创建一个接受者,带有接收消息的方法,代码如下:

  1. package cn.it1995.demo;
  2. import org.slf4j.Logger;
  3. import org.slf4j.LoggerFactory;
  4. import java.util.concurrent.atomic.AtomicInteger;
  5. public class Receiver {
  6. private static final Logger LOGGER = LoggerFactory.getLogger(Receiver.class);
  7. private AtomicInteger counter = new AtomicInteger();
  8. public void receiveMessage(String message){
  9. LOGGER.info("Received <" + message + ">");
  10. counter.incrementAndGet();
  11. }
  12. public int getCount(){
  13. return counter.get();
  14. }
  15. }

Receiver为POJO类定义了接收数据的方法。这里是要注册消息监听器监听Receiver的receiveMessage方法。

注册监听者及消息发布者

Spring Data Redis提供了send和receive的Redis等组件,要想使用这些功能需要下面3个配置:

  1. A connection factory

  2. A message listener container

  3. A redis template

使用Redis template发送消息,将Receiver注册到监听容器里面,用于监听消息。connection factory包含了template和message listener连接redis服务的链接。

下面的代码使用了Spring Boot的默认的RedisConnectionFactory,这个类其实就是基于JedisConnectionFactory,这个JedisConnectionFactory是基于Jedis Redis库。连接工厂会被注入message listener容器和Redis template。代码如下:

  1. package cn.it1995.demo;
  2. import org.slf4j.Logger;
  3. import org.slf4j.LoggerFactory;
  4. import org.springframework.boot.SpringApplication;
  5. import org.springframework.boot.autoconfigure.SpringBootApplication;
  6. import org.springframework.context.ConfigurableApplicationContext;
  7. import org.springframework.context.annotation.Bean;
  8. import org.springframework.data.redis.connection.RedisConnectionFactory;
  9. import org.springframework.data.redis.core.StringRedisTemplate;
  10. import org.springframework.data.redis.listener.PatternTopic;
  11. import org.springframework.data.redis.listener.RedisMessageListenerContainer;
  12. import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
  13. @SpringBootApplication
  14. public class DemoApplication {
  15. private static final Logger LOGGER = LoggerFactory.getLogger(DemoApplication.class);
  16. public static void main(String[] args) throws InterruptedException {
  17. ConfigurableApplicationContext ctx = SpringApplication.run(DemoApplication.class, args);
  18. StringRedisTemplate template = ctx.getBean(StringRedisTemplate.class);
  19. Receiver receiver = ctx.getBean(Receiver.class);
  20. while(receiver.getCount() == 0){
  21. LOGGER.info("Sending message...");
  22. template.convertAndSend("chat", "Hello From Redis");
  23. Thread.sleep(500L);
  24. }
  25. }
  26. @Bean
  27. StringRedisTemplate template(RedisConnectionFactory connectionFactory){
  28. return new StringRedisTemplate(connectionFactory);
  29. }
  30. @Bean
  31. RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory, MessageListenerAdapter listenerAdapter){
  32. RedisMessageListenerContainer container = new RedisMessageListenerContainer();
  33. container.setConnectionFactory(connectionFactory);
  34. container.addMessageListener(listenerAdapter, new PatternTopic("chat"));
  35. return container;
  36. }
  37. @Bean
  38. MessageListenerAdapter listenerAdapter(Receiver receiver){
  39. return new MessageListenerAdapter(receiver, "receiveMessage");
  40. }
  41. @Bean
  42. Receiver receiver(){
  43. return new Receiver();
  44. }
  45. }

listenrAdpter方法将Receiver类的receiveMessage方法注册到消息监听容器中,将会监听chat通道的数据。

application.properties:

  1. # Redis服务器连接端口
  2. spring.redis.port=6379
  3. # Redis服务器地址
  4. spring.redis.host=127.0.0.1
  5. # Redis数据库索引(默认为0)
  6. spring.redis.database=0
  7. # Redis服务器连接密码(默认为空)
  8. spring.redis.password=xxxxx
  9. # 连接池最大连接数(使用负值表示没有限制)
  10. spring.redis.jedis.pool.max-active=8
  11. # 连接池最大阻塞等待时间(使用负值表示没有限制)
  12. spring.redis.jedis.pool.max-wait=30000ms
  13. # 连接池中的最大空闲连接
  14. spring.redis.jedis.pool.max-idle=8
  15. # 连接池中的最小空闲连接
  16. spring.redis.jedis.pool.min-idle=0
  17. # 连接超时时间(毫秒)
  18. spring.redis.timeout=5000ms

程序运行截图如下:

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxNzg0NDI3NjE_size_16_color_FFFFFF_t_70

发表评论

表情:
评论列表 (有 0 条评论,263人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Spring Boot文档阅读

    原因之初 最初习惯百度各种博客教程,然后跟着操作,因为觉得跟着别人走过的路走可以少走很多弯路,省时间。然而,很多博客的内容并不够完整,甚至错误,看多了的博客甚至有千篇一律的感