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

引言

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

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


优势:

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

     org.springframework.boot
     spring-boot-starter-data-redis

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 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中进行调用。

你可能感兴趣的:(redis,数据库,缓存,消息队列)