Springboot项目中使用Redis作为消息队列

引言

现在在软件开发中,消息队列扮演着至关重要的角色,它帮助我们解耦系统组件,实现异步处理,提高系统的可扩展性和弹性。Redis,这个著名的键值存储系统,不仅仅限于数据缓存,其灵活的数据结构和快速的内存操作也使其成为构建轻量级消息队列的理想选择。

Redis作为消息队列的优势与局限


优势:

  • 轻量级:易于部署和维护,特别适合小规模或快速原型开发。
  • 高性能:基于内存的操作,极低的延迟。
  • 灵活性:多种数据结构适应不同场景。
  • 集成简便:对于已使用Redis作为缓存的系统。
局限:
  • 消息丢失风险:特别是使用List结构时,消息未被确认即可能丢失。
  • 幂等性问题:缺乏原生支持,需要业务逻辑层自行处理重复消费问题。
  • 复杂场景支持有限:对于事务消息、顺序消息等高级需求,不如专业消息队列如RocketMQ、RabbitMQ等强大。
使用案例
1、引入依赖
<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

2、消息队列Springboot的Config配置


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.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 * 设置redis消息监听
 */

@Configuration
public class RedisMqConfig {

    //自定义消费者
    @Autowired
    private RedisMessageSubscriber redisMessageSubscriber;

    @Bean
    public RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.addMessageListener(new MessageListenerAdapter(redisMessageSubscriber), new ChannelTopic(ChannelTopicConstant.CHANNEL_TOPIC));
        return container;
    }

}

3、发布者

@Service
public class RedisMessagePublisher {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    //channel类似为发布的主题
    public void publish(String channel, Object message) {
        redisTemplate.convertAndSend(channel, message);
    }
}
4、消费者
@Service
@Slf4j
public class RedisMessageSubscriber implements MessageListener {

    @Autowired
    private IUnattendedHandleDataService unattendedHandleDataService;
    @Override
    public void onMessage(Message message, byte[] pattern) {
        String messageStr = new String(message.getBody());
        // 处理接收到的消息
        log.info("received message:{}",messageStr);
        if (messageStr.startsWith("\"") && messageStr.endsWith("\"")) {
            messageStr = messageStr.substring(1, messageStr.length() - 1);
        }
        if (messageStr.contains("\\")) {
            messageStr = messageStr.replace("\\", "");
        }
        JSONObject jsonObject = JSON.parseObject(messageStr,JSONObject.class);
        //执行业务逻辑
    }
}

可以在config配置中设置多个消费者。

5、调用
redisMessagePublisher.publish(ChannelTopicConstant.CHANNEL_TOPIC,data.toJSONString());

可以在Controller或其他Service中进行调用。

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

StruggleRookie

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值