springboot redis 实现消息队列

本文涉及的产品
云数据库 Redis 版,社区版 2GB
推荐场景:
搭建游戏排行榜
简介: springboot redis 实现消息队列

Redis 消息队列适用于以下场景:

1. 异步处理:当一个操作需要花费较长时间才能完成时,可以使用消息队列将任务放入队列中,让后台进程异步地处理这些任务。这样可以避免阻塞主线程,提高系统的响应速度和吞吐量。

2. 解耦系统组件:在微服务架构中,不同的服务之间可以通过消息队列进行通信,实现松耦合。这样即使某个服务出现故障,其他服务仍然可以正常运作。

3. 流量削峰:在高并发场景下,系统可能会面临瞬时流量激增的情况。使用消息队列可以将这些请求暂存起来,然后按照系统的处理能力逐步处理,避免系统因为瞬时流量过大而崩溃。

4. 延迟处理:有些业务逻辑需要在特定的时间点执行,例如发送邮件、短信等。通过消息队列,可以将这类任务放入队列中,等到指定的时间再进行处理。

5. 分布式事务:在分布式系统中,多个服务可能需要共同完成一个业务操作。通过消息队列,可以确保各个服务之间的操作顺序和一致性。

6. 事件驱动:在事件驱动架构中,各个服务之间通过发布和订阅事件进行通信。消息队列可以作为事件的传输媒介,实现不同服务之间的协同工作。

总之,Redis 消息队列适用于需要异步处理、解耦、流量削峰、延迟处理、分布式事务和事件驱动等场景。

在Spring Boot中使用Redis作为消息队列的实现:

1. 添加依赖

在`pom.xml`文件中添加Spring Boot Redis和Jedis的依赖:

```xml
<dependencies>
    <!-- Spring Boot Redis -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    <!-- Jedis -->
    <dependency>
        <groupId>redis.clients</groupId>
        <artifactId>jedis</artifactId>
    </dependency>
</dependencies>
```

2. 配置Redis

在`application.properties`文件中配置Redis连接信息:

```properties
spring.redis.host=localhost
spring.redis.port=6379
```

3. 创建生产者

创建一个生产者类,用于发送消息到Redis消息队列:


```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
@Component
public class Producer {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    public void sendMessage(String key, String message) {
        redisTemplate.convertAndSend(key, message);
    }
}
```


4. 创建消费者

创建一个消费者类,用于从Redis消息队列接收消息:

```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
@Component
public class Consumer implements MessageListener {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Override
    public void onMessage(Message message, byte[] pattern) {
        System.out.println("Received message: " + message.toString());
    }
}
```


5. 配置消费者监听

在配置类中,将消费者添加到Redis消息队列的监听器列表中:

```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
public class RedisConfig {
    @Autowired
    private Consumer consumer;
    @Bean
    public RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
                                                  MessageListenerAdapter listenerAdapter) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.addMessageListener(listenerAdapter, topic());
        return container;
    }
    @Bean
    public MessageListenerAdapter listenerAdapter() {
        return new MessageListenerAdapter(consumer, "onMessage");
    }
    @Bean
    public ChannelTopic topic() {
        return new ChannelTopic("messageQueue");
    }
}
```


6. 测试发送和接收消息


在Spring Boot应用的主类中,注入生产者并发送一条消息:


```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application implements CommandLineRunner {
    @Autowired
    private Producer producer;
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
    @Override
    public void run(String... args) throws Exception {
        producer.sendMessage("messageQueue", "Hello, Redis!");
    }
}
```
运行应用后,控制台将输出接收到的消息:
```
Received message: Hello, Redis!
```
相关实践学习
基于Redis实现在线游戏积分排行榜
本场景将介绍如何基于Redis数据库实现在线游戏中的游戏玩家积分排行榜功能。
云数据库 Redis 版使用教程
云数据库Redis版是兼容Redis协议标准的、提供持久化的内存数据库服务,基于高可靠双机热备架构及可无缝扩展的集群架构,满足高读写性能场景及容量需弹性变配的业务需求。 产品详情:https://www.aliyun.com/product/kvstore &nbsp; &nbsp; ------------------------------------------------------------------------- 阿里云数据库体验:数据库上云实战 开发者云会免费提供一台带自建MySQL的源数据库&nbsp;ECS 实例和一台目标数据库&nbsp;RDS实例。跟着指引,您可以一步步实现将ECS自建数据库迁移到目标数据库RDS。 点击下方链接,领取免费ECS&amp;RDS资源,30分钟完成数据库上云实战!https://developer.aliyun.com/adc/scenario/51eefbd1894e42f6bb9acacadd3f9121?spm=a2c6h.13788135.J_3257954370.9.4ba85f24utseFl
目录
相关文章
|
25天前
|
NoSQL Java Redis
SpringBoot集成Redis解决表单重复提交接口幂等(亲测可用)
SpringBoot集成Redis解决表单重复提交接口幂等(亲测可用)
279 0
|
30天前
|
NoSQL Java Redis
SpringBoot集成Redis
SpringBoot集成Redis
424 0
|
8天前
|
NoSQL 数据可视化 Java
Springboot整合redis
Springboot整合redis
|
9天前
|
人工智能 前端开发 Java
Java语言开发的AI智慧导诊系统源码springboot+redis 3D互联网智导诊系统源码
智慧导诊解决盲目就诊问题,减轻分诊工作压力。降低挂错号比例,优化就诊流程,有效提高线上线下医疗机构接诊效率。可通过人体画像选择症状部位,了解对应病症信息和推荐就医科室。
148 10
|
12天前
|
消息中间件 缓存 NoSQL
Redis stream 用做消息队列完美吗
Redis Stream 是 Redis 5.0 版本中引入的一种新的数据结构,它用于实现简单但功能强大的消息传递模式。 这篇文章,我们聊聊 Redis Stream 基本用法 ,以及如何在 SpringBoot 项目中应用 Redis Stream 。
Redis stream 用做消息队列完美吗
|
18天前
|
NoSQL Java Redis
Springboot整合redis
Springboot整合redis
|
26天前
|
NoSQL Java Redis
SpringBoot集成Redis
SpringBoot集成Redis
54 1
|
1月前
|
缓存 NoSQL Java
springboot中集成redis,二次封装成工具类
springboot中集成redis,二次封装成工具类
174 0
|
存储 SQL 消息中间件
springboot整合redis
redis是一个支持key-value的数据库,数据全部在内存中处理,在在一定时间间隔中将数据固化到磁盘。因为是内存操作,所以速度特别快。(这里我们主要介绍redis作为缓存使用)
176 0
springboot整合redis
|
存储 缓存 NoSQL
SpringBoot整合Redis
SpringBoot整合Redis
329 0
SpringBoot整合Redis