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

首先要启动Redis服务端

redis-server

redis启动后会有如下信息:

[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
[35142] 01 May 14:36:28.940 * Max number of open files set to 10032
                _._
              _.-``__ ''-._
        _.-``    `.  `_.  ''-._           Redis 2.6.12 (00000000/0) 64 bit
    .-`` .-```.  ```\/    _.,_ ''-._
  (    '      ,       .-`  | `,    )     Running in stand alone mode
  |`-._`-...-` __...-.``-._|'` _.-'|     Port: 6379
  |    `-._   `._    /     _.-'    |     PID: 35142
    `-._    `-._  `-./  _.-'    _.-'
  |`-._`-._    `-.__.-'    _.-'_.-'|
  |    `-._`-._        _.-'_.-'    |           https://redis.io
    `-._    `-._`-.__.-'_.-'    _.-'
  |`-._`-._    `-.__.-'    _.-'_.-'|
  |    `-._`-._        _.-'_.-'    |
    `-._    `-._`-.__.-'_.-'    _.-'
        `-._    `-.__.-'    _.-'
            `-._        _.-'
                `-.__.-'

[35142] 01 May 14:36:28.941 # Server started, Redis version 2.6.12
[35142] 01 May 14:36:28.941 * The server is now ready to accept connections on port 6379

Maven配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.1</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>cn.it1995</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <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-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

创建Redis消息接受者

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

package cn.it1995.demo;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.atomic.AtomicInteger;

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();
    }
}

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。代码如下:

package cn.it1995.demo;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;

@SpringBootApplication
public class DemoApplication {

    private static final Logger LOGGER = LoggerFactory.getLogger(DemoApplication.class);

    public static void main(String[] args) throws InterruptedException {

        ConfigurableApplicationContext ctx = SpringApplication.run(DemoApplication.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);
        }
    }

    @Bean
    StringRedisTemplate template(RedisConnectionFactory connectionFactory){

        return new StringRedisTemplate(connectionFactory);
    }

    @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();
    }
}

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

 

application.properties:

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

程序运行截图如下:

已标记关键词 清除标记
springboot学习笔记 spring基础 Spring概述 Spring的简史 xml配置 注解配置 java配置 Spring概述 Spring的模块 核心容器CoreContainer Spring-Core Spring-Beans Spring-Context Spring-Context-Support Spring-Expression AOP Spring-AOP Spring-Aspects Messaging Spring-Messaging WEB Spring-Web Spring-Webmvc Spring-WebSocket Spring-Webmvc-Portlet 数据访问/集成(DataAccess/Intefration) Spring-JDBC Spring-TX Spring-ORM Spring-OXM Spring-JMS Spring的生态 Spring Boot Spring XD Spring Cloud Spring Data Spring Integration Spring Batch Spring Security Spring HATEOAS Spring Social Spring AMQP Spring Mobile Spring for Android Spring Web Flow Spring Web Services Spring LDAP Spring Session Spring项目快速搭建 Maven简介 Maven安装 Maven的pom.xml dependencies dependency 变量定义 编译插件 Spring项目的搭建 Spring Tool Suite https://spring.io/tools/sts/all IntelliJ IDEA NetBeans https://netbeans.org/downloads/ Spring基础配置 依赖注入 声明Bean的注解 @Component组件,没有明确的角色 @Service在业务逻辑层(service层) @Repository在数据访问层(dao层) @Controller在展现层(MVC→SpringMVC) 注入Bean的注解 @Autowired:Spring提供的注解 @Inject:JSR-330提供的注解 @Resource:JSR-250提供的注解 Java配置 @Configuration声明当前类是一个配置类 @Bean注解在方法上,声明当前方法的返回值为一个Bean AOP @Aspect 声明是一个切面 拦截规则@After @Before @Around PointCut JoinPoint Spring常用配置 Bean的Scope Singleton Prototype Request Session GlobalSession SpringEL和资源调用 注入普通字符 注入操作系统属性 注入表达式云算结果 注入其他Bean的属性 注入文件内容 注入网址内容 注入属性文件 Bean的初始化和销毁 Java配置方式 注解方式 Profile @Profile 通过设定jvm的spring.profiles.active参数 web项目设置在Servlet的context parameter中 事件Application Event 自定义事件,集成ApplicationEvent 定义事件监听器,实现ApplicationListener 使用容器发布事件 Spring高级话题 Spring Aware BeanNameAware BeanFactoryAware ApplicationContextAware MessageSourceAware ApplicationEventPublisherAware ResourceLoaderAware 多线程 计划任务 cron fixDelay fixRate 条件注解@Conditional 组合注解与元注解 @Enable*注解的工作原理 直接导入配置类 依据条件选择配置类 动态注册Bean 测试 Spring TestContext Framework集成测试 SpringMVC基础 Spring MVC概述 SpringMVC项目快速搭建 构建Maven项目 日志配置 演示页面 Spring MVC配置 Web配置 简单控制器 运行 Spring MVC的常用注解 @Controller @RequestMapping @ResponseBody @RequestBody @PathVariable @RestController Spring MVC的基本配置 静态资源映射 拦截器配置 @ControllerAdivce @ExceptionHandler @InitBinder @ModelAttribute 其他配置 ViewController 路径匹配参数配置 WebMvcConfigurerAdapter WebMvcConfigurer Spring MVC的高级配置 文件上传配置 自定义HttpMessageConverter MappingJackson2HttpMessageConverter StringHttpMessageConverter 服务器端推送技术 SSE Servlet3.0+异步方法处理 Spring MVC的测试 MockMVC MockHttpServlerRequest MockHttpServletResponse MockHttpSession SpringBoot基础 SpringBoot概述 什么是SpringBoot SpringBoot核心功能 独立运行的Spring项目 内嵌Servlet容器 提供Starter简化Maven配置 自动配置Spring 准生产的应用监控 无代码声称和xml配置 SpringBoot的优缺点 优点 快速构建项目 对主流开发框架的无配置集成 项目可独立运行,无需外部依赖Servlet容器 提供运行时的应用监控 极大地提高了开发,部署效率 与云计算的天然集成 缺点 书籍文档较少,且不够深入 SpringBoot版本 SpringBoot快速搭建 http://start.spring.io SpringToolSuite InterlliJIDEA SpringBootCLI Maven手工构建 简单演示 SpringBoot核心 基本配置 入口类和@SpringBootApplication @Configuration @EnableAutoConfiguration @ComponentScan 关闭特定的自动配置 定制Banner 修改Banner 关闭Banner main里修改 fluentAPI SpringBoot的配置文件 application.properties application.yml src/main/resources starter pom 官方starter pom spring-boot-starter spring-boot-starter-actuator spring-boot-starter-remote-shell spring-boot-starter-amqp spring-boot-starter-aop spring-boot-starter-batch spring-boot-starter-cache spring-boot-starter-cloud-connectors spring-boot-starter-data-elasticsearch spring-boot-starter-data-gemfire spring-boot-starter-data-jpa spring-boot-starter-data-mongodb spring-boot-starter-data-rest spring-boot-starter-data-solr spring-boot-starter-freemarker spring-boot-starter-groovy-templates spring-boot-starter-hateoas spring-boot-starter-hornetq spring-boot-starter-integration spring-boot-starter-jdbc spring-boot-starter-jerscy spring-boot-starter-jta-atomikos spring-boot-starter-jta-bitronix spring-boot-starter-mail spring-boot-starter-mobile spring-boot-starter-mustache spring-boot-starter-redis spring-boot-starter-security spring-boot-starter-social-facebook spring-boot-starter-social-linkedin spring-boot-starter-social-twitter spring-boot-starter-test spring-boot-starter-thymeleaf spring-boot-starter-velocity spring-boot-starter-web spring-boot-starter-
相关推荐
©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页