一、安装Erlang与Rabbitmq
二、在springboot中使用rabbitmq
1.导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
2.编写配置文件
spring:
rabbitmq:
host: localhost
port: 5672
username: guest
password: guest
3.配置一个队列
package com.example.Rabbtimq.config;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class QueueAndExchangeConfig {
@Bean("myFirstQueue")
public Queue getFirstQueue(){
return new Queue("my-first-queue");
}
}
4.编写一个生产者类
package com.example.Rabbtimq.controller;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("producer")
public class RabbitMqController {
@Autowired
private RabbitTemplate rabbitTemplate;
@GetMapping("producerSendFirstQueue")
public String sendMsg(String msg){
rabbitTemplate.convertAndSend("my-first-queue",msg);
return msg;
}
}
5.编写一个消费者监听队列中的消息
package com.example.Rabbtimq.controller;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@Component
public class ConsumerHandler {
@RabbitListener(queues = "my-first-queue")
public void getFirstQueue(String msg){
System.out.println("消费者1:"+msg);
}
}
6.使用接口工具调生产接口
7.查看图形化界面