1.引入RabbitMQ 包
<!--RabbitMQ-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
2.编写配置文件
spring:
rabbitmq:
host: 66.666.66.66 #IP地址
port: 5672 #端口号
username: guest
password: guest
3.编写生产者
@Autowired
private RabbitTemplate rabbitTemplate;
/**
* 获取用户的邮箱,放到rabbitmq消息队列里面去
* @return
*/
@RequestMapping("/sendMessage")
public void sendMessageToRabbitMQ(){
String message= "123456";
//这里helloQueue是队列名
rabbitTemplate.convertAndSend("helloQueue",message);
}
4.编写消费者
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
@RabbitListener(queuesToDeclare = @Queue("helloQueue"))
public class EmailLister {
@RabbitHandler
public void sendEmail(String message){
system out println(message);
}
}