Spring Boot使用Redis消息队列

2019-05-15  本文已影响0人  十毛tenmao

业务系统经常需要用到MQ消息队列,但是又不希望引入一个完整的中间件,比如RocketMQRabbitMQ,因为会增加接入成本和运维成本。所以当业务量不是很大,且一致性要求不是很强的场景下,可以选择Redis,使用其pub/sub机制作为消息队列的实现

添加依赖


<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.6</version>
    </dependency>
</dependencies>

消息监听器


package com.tenmao;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.lang.NonNull;

@Slf4j
public class MyMessageListener implements MessageListener {
    @Override
    public void onMessage(@NonNull Message message, byte[] pattern) {
        log.info("message received: {}", message);
    }
}

定义消息监听相关的Bean


@SpringBootApplication
public class RedisMqApplication {

    public static void main(String[] args) {
        SpringApplication.run(RedisMqApplication.class, args);
    }

    /**
     * RedisMessageListenerContainer提供订阅消息的多路分发,这样多个订阅可以共享同一个Redis连接.
     */
    @Bean
    RedisMessageListenerContainer redisContainer(RedisConnectionFactory connectionFactory) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.addMessageListener(new MyMessageListener(), new ChannelTopic("tenmao.blog.channel"));
        return container;
    }
}

消息发送


@RestController
public class HomeController {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping
    public String ping() {
        //往tenmao.blog.channel发送消息"hello world"
        stringRedisTemplate.convertAndSend("tenmao.blog.channel", "hello world");
        return "success";
    }
}

参考

上一篇下一篇

猜你喜欢

热点阅读