springboot下rabbitmq的簡單使用

這篇文章中介紹瞭如何安裝rabbitmq,以及注意事項。

https://blog.csdn.net/qq_27224549/article/details/92084129

1.pom中添加相關的starter依賴。

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

2.配置文件中加入相關配置信息

#rabbitmq
spring.rabbitmq.host=127.0.0.1
spring.rabbitmq.port=5672
spring.rabbitmq.username=admin
spring.rabbitmq.password=admin

3.隊列的簡單使用。

先創建一個隊列。然後創建一個隊列的發送者(生產者)。在創建隊列的接收者(消費者)。

創建隊列

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.amqp.core.Queue;
@Configuration
public class RabbitConfig {
	    @Bean
	    public Queue Queue() {        
	        return new Queue("hello");
	    }

}

生產者

import java.util.Date;

import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class HelloSender {
	@Autowired
    private AmqpTemplate rabbitTemplate;    
    
    public void send() {
        String context = "hello " + new Date();
        System.out.println("Sender : " + context);        
        this.rabbitTemplate.convertAndSend("hello", context);
    }
}

消費者

import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
@RabbitListener(queues = "hello")
public class HelloReceiver {
	@RabbitHandler
    public void process(String hello) {
        System.out.println("Receiver  : " + hello);
    }
}

測試

在Controller中注入生產者,直接調用send方法即可。

@RequestMapping("/hello")    
    public String index() { 
		helloSender.send();
        return "Hello World";
    }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章