springboot 往redis的队列推数据,每次取出就会移除的具体实现代码
时间: 2024-09-30 16:16:15 浏览: 45
微服务SpringBoot整合Redis基于Redis的Stream消息队列实现异步秒杀下单
5星 · 资源好评率100%
Spring Boot 中使用 Redis 的列表(List)作为消息队列,并实现实时推送和消费,通常会涉及到 `RedisTemplate` 和 `JedisTemplate`。下面是一个简单的示例,展示如何往队列中添加数据并消费:
首先,你需要添加 Redis 配置到 `application.properties` 或者 `application.yml` 文件中:
```properties
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=<your_password>
```
然后,在 Spring Boot 应用中,引入相关依赖:
```xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-redis</artifactId>
</dependency>
</dependencies>
```
创建一个 Redis 操作的配置类 `RedisConfig.java`:
```java
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
public class RedisConfig {
@Bean
public StringRedisSerializer stringRedisSerializer() {
return new StringRedisSerializer();
}
@Bean
public JedisConnectionFactory jedisConnectionFactory() {
// 如果需要密码,请添加
return new JedisConnectionFactory("localhost", 6379);
}
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setKeySerializer(stringRedisSerializer());
template.setValueSerializer(new GenericToStringSerializer<>(Object.class));
template.setConnectionFactory(factory);
return template;
}
}
```
接下来,创建一个生产者类,比如 `MessageProducer.java`:
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.stereotype.Component;
@Component
public class MessageProducer {
private final ListOperations<String, Object> operations;
@Autowired
public MessageProducer(RedisTemplate<String, Object> redisTemplate) {
this.operations = redisTemplate.opsForList();
}
public void push(String queueName, String message) {
operations.rightPush(queueName, message); // 添加到列表右侧
}
}
```
最后,创建一个消费者类 `MessageConsumer.java` 来消费消息并移除:
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class MessageConsumer {
private final ListOperations<String, Object> operations;
@Autowired
public MessageConsumer(RedisTemplate<String, Object> redisTemplate) {
this.operations = redisTemplate.opsForList();
}
public void consume(String queueName) {
for (String msg : operations.leftRange(queueName, 0, -1)) { // 从左侧开始取,每取一次删除一个
System.out.println("Consumed message: " + msg);
operations.lRem(queueName, 1, msg); // 移除已消费的消息
}
}
}
```
在使用时,只需在生产者类上注入 `@Autowired`,然后创建消息并推送到指定队列,而在消费者类上,定时或者事件触发时调用 `consume()`。
阅读全文