版权声明:转载请写明出处 https://blog.csdn.net/huijiangu4621/article/details/83622902
在pom文件中导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
在application.properties中添加如下配置信息
spring.rabbitmq.host=192.168.43.127(这里配置自己的虚机地址)
spring.rabbitmq.port=5672
spring.rabbitmq.username=admin
spring.rabbitmq.password=admin
创建队列
package com.etoak.crazy.config.rabbitmq;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RabbitMQConfig {
@Bean
public Queue queue() {
//创建队列名为TEST的队列
return new Queue("TEST");
}
}
创建生产者
package com.etoak.crazy.study.rabbitmq.producer;
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 ProducerDemo {
@Autowired
private AmqpTemplate rabbitTemplate;
public void send() {
String message = "hello!Now the time is " + new Date();
System.out.println("发送的信息为 : " + message);
//发送message给名为TEST的队列
this.rabbitTemplate.convertAndSend("TEST", message);
}
}
创建消费者
package com.etoak.crazy.study.rabbitmq.consumer;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
@Component
//监听名为TEST的队列
@RabbitListener(queues = "TEST")
public class ConsumerDemo {
//@RabbitListener 标注在类上面表示当有收到消息的时候,就交给 @RabbitHandler 的方法处理,具体使用哪个方法处理
@RabbitHandler
public void process(String message) {
System.out.println("接收消息为 : " + message);
}
}
测试类测试
package com.etoak.crazy.test.rabbitmq;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.etoak.crazy.study.rabbitmq.producer.ProducerDemo;
@RunWith(SpringRunner.class)
@SpringBootTest
public class RabbitmqDemoTest {
@Autowired
private ProducerDemo producerdemo;
@Test
public void hello() throws Exception {
producerdemo.send();
}
}
在虚拟机中service rabbitmq-server start输入开启RabbitMQ服务
启动后输入service rabbitmq-server status查看RabbitMQ服务状态
测试结果: