Spring Boot + RabbitMq

此篇使用RabbitMq來做消息的推送。

1.pom.xml加入依賴

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-amqp</artifactId>
  <version>2.3.5.RELEASE</version>
</dependency>

2.application.properties加入RabbitMq相關設定

spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.activemq.user=guest
spring.activemq.password=guest

3.加入RabbitmqConfig

package com.liongogo.configuration;

import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.annotation.EnableRabbit;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableRabbit
public class RabbitmqConfig {
    @Bean
    public Queue lionGoGoQueue() {
        return new Queue("liongogo.test.queue");
    }
}

4.建立MqDto

package com.liongogo.mq;

import java.io.Serializable;

public class MqDto implements Serializable {

    public MqDto(){

    }

    public MqDto(Object body){
        this.setBody(body);
    }
    private Object body;

    public Object getBody() {
        return body;
    }

    public void setBody(Object body) {
        this.body = body;
    }
}

5.監聽MQ

package com.liongogo.listener;

import com.liongogo.mq.MqDto;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
@RabbitListener(queues={"liongogo.test.queue"})
public class LionGoGoTestQueueListener {

    @RabbitHandler
    public void receive(MqDto mqDto) {
        System.out.println("從queue中接收到消息:"+mqDto.getBody());
    }
}

6.發佈消息

package com.liongogo.controller;

import com.liongogo.domain.SuperHero;
import com.liongogo.mq.MqDto;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {

    @Autowired
    RabbitTemplate rabbitTemplate;
    
    @RequestMapping("/mq/send")
    public String sendToQueue() {
        rabbitTemplate.convertAndSend("liongogo.test.queue", new MqDto("liongogo"));
        return "發佈消息成功";
    }
}