天天看點

企業級 SpringBoot 教程-在springboot中用redis實作消息隊列

準備階段

java 1.8

maven 3.0

idea

環境依賴

建立一個新的springboot工程,在其pom檔案,加入spring-boot-starter-data-redis依賴:

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>           

建立一個消息接收者 REcevier類,它是一個普通的類,需要注入到springboot中。

public class Receiver {
    private static final Logger LOGGER = LoggerFactory.getLogger(Receiver.class);

    private CountDownLatch latch;

    @Autowired
    public Receiver(CountDownLatch latch) {
        this.latch = latch;
    }

    public void receiveMessage(String message) {
        LOGGER.info("Received <" + message + ">");
        latch.countDown();
    }
}           

注入消息接收者

@Bean
    Receiver receiver(CountDownLatch latch) {
        return new Receiver(latch);
    }

    @Bean
    CountDownLatch latch() {
        return new CountDownLatch(1);
    }

    @Bean
    StringRedisTemplate template(RedisConnectionFactory connectionFactory) {
        return new StringRedisTemplate(connectionFactory);
    }           

注入消息監聽容器 在spring data redis中,利用redis發送一條消息和接受一條消息,需要三樣東西:

一個連接配接工廠 一個消息監聽容器 Redis template 上述1、3步已經完成,是以隻需注入消息監聽容器即可:

@Bean
    RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
                                            MessageListenerAdapter listenerAdapter) {

        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.addMessageListener(listenerAdapter, new PatternTopic("chat"));

        return container;
    }

    @Bean
    MessageListenerAdapter listenerAdapter(Receiver receiver) {
        return new MessageListenerAdapter(receiver, "receiveMessage");
    }           

測試在springboot入口的main方法:

public static void main(String[] args) throws Exception{
        ApplicationContext ctx =  SpringApplication.run(SpringbootRedisApplication.class, args);

        StringRedisTemplate template = ctx.getBean(StringRedisTemplate.class);
        CountDownLatch latch = ctx.getBean(CountDownLatch.class);

        LOGGER.info("Sending message...");
        template.convertAndSend("chat", "Hello from Redis!");

        latch.await();

        System.exit(0);
    }