1. 程式人生 > >三分鐘學會在spring boot 專案中使用RabbitMq做訊息佇列

三分鐘學會在spring boot 專案中使用RabbitMq做訊息佇列

第一步:在spring boot專案中新增RabbitMq的maven依賴

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

第二步:在配置檔案中新增RabbitMq的配置

#配置RabbitMQ
spring.rabbitmq.host=192.168.1.103
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
spring.rabbitmq.publisherConfirms=true

第三步:新增RabbitMq配置類

import org.springframework.amqp.core.Queue;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Bean;

@Configurable
public class RabbitMqConfig {

    @Bean
    public Queue countPalletBatchQueue(){
        return new Queue("count-pallet-batch-queue");    
    };
}

第四步:新增生產者類

@Component
public class producter {

   

    @Autowired
    private AmqpTemplate amqpTemplate;


    void create() {
        String message = "這是一條訊息";
        amqpTemplate.convertAndSend("count-pallet-batch-queue",message);
    }

     
}

第五步:新增消費者類

@Component
@Service
@Transactional
public class  customer {

 

    @Autowired
    private AmqpTemplate amqpTemplate;

 

    @RabbitListener(queues = "count-pallet-batch-queue")
    public String custom(String message){
        return message;
    }


}

OK