下载安装:
在自己的虚拟机上面用命令下载
docker pull registry.docker-cn.com/library/rabbitmq:3.6-management management表示是带管理页面的
启动:
docker run -d -p 5672:5672 -p 15672:15672 --name myrabbitmq 3951818b0610
然后配置一个转化器(转成json),rabbitmqTemplate操作发送和接收消息
@Configuration
public class myConfig {
@Bean
public MessageConverter messageConverter() {
return new Jackson2JsonMessageConverter();
}
}
配置文件
spring:
rabbitmq:
host: 192.168.1.113
username: guest
password: guest
virtual-host: /
port: 5672
测试:rabbitmqTemplate操作发送和接收消息
/**
* 单播
*/
@Test
public void test1() {
// Message需要自己构建一个自定义的消息内容和消息体
// rabbitTemplate.send(exchange,routingKey,message);
Map map = new HashMap<>();
map.put("msg","这是一个消息");
map.put("", Arrays.asList("newsjj",true,1));
//对象被序列号后发送出去
rabbitTemplate.convertAndSend("exchange.direct","atguigu.news",map);
}
@Test
public void receive() {
// Message atguigu = rabbitTemplate.receive("atguigu");
Object atguigui = rabbitTemplate.receiveAndConvert("atguigui");
System.out.print(atguigui.getClass());
System.out.println(atguigui);
}
/**
* 广播
*/
@Test
public void sendMsg(){
rabbitTemplate.convertAndSend("exchange.fanout","",new Book("红楼梦","曹雪芹"));
}
@EnableRabbit + @RabbitListener 监听消息队列的内容
@EnableRabbit 在主main方法开启基于注解的rabbit
@RabbitListener(queues = "atguigu.news")
public void receive(Book book){
System.out.println("收到消息:"+book);
}
@RabbitListener(queues = "atguigu")
public void receive02(Message message){
System.out.println(message.getBody());
System.out.println(message.getMessageProperties());
}
AmqpAdmin : RabbitMQ系统管理功能组件;
AmqpAdmin:创建和删除 Queue,Exchange,Binding
@Test
public void createExchange(){
//创建exchange
amqpAdmin.declareExchange(new DirectExchange("amqpadmin.exchange"));
System.out.println("创建完成");
}
@Test
public void createExchange(){
//创建queue
amqpAdmin.declareQueue(new Queue("amqpadmin.queue",true));
}
@Test
public void createExchange(){
// 创建banding
amqpAdmin.declareBinding(new Binding("amqpadmin.queue",
Binding.DestinationType.QUEUE,"amqpadmin.exchange","amqp.haha",null));
}