package com.shi.amqp;
import com.shi.amqp.model.Book;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.amqp.core.AmqpAdmin;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@RunWith(SpringRunner.class)
@SpringBootTest
public class AmqpApplicationTests {
@Autowired
RabbitTemplate rabbitTemplate;
@Autowired
AmqpAdmin amqpAdmin;
@Test
public void contextLoads() {
}
@Test
public void create(){
amqpAdmin.declareQueue(new Queue("amqp.queue"));//创建队列
System.out.println("队列创建成功");
amqpAdmin.declareExchange(new DirectExchange("ampq.exchage"));//创建直连型交换机
System.out.println("交换机创建成功");
amqpAdmin.declareBinding(new Binding("amqp.queue",
Binding.DestinationType.QUEUE,"ampq.exchage","amqp",null));//绑定信息
System.out.println("队列与交换机的绑定创建成功");
}
/**
* 1 单播 (点对点)
*/
@Test
public void sendMessage(){
//message 需要自己构造一个,定义消息体内容和消息头
//rabbitTemplate.send(exchange,routingKey,message);
//obj 默认当成消息体,只需要传入要发送的对象,自动序列化发送给rabbitMq
//rabbitTemplate.convertAndSend(exchange,routingKey, obj);
/*Map<String,Object> map = new HashMap<>();
map.put("msg","我的测试直连消息队列");
map.put("date",new Date());
rabbitTemplate.convertAndSend("amq.direct","direct",map);
*/
Book book = new Book();
book.setName("三国演义3333");
book.setAuthor("罗贯中3333");
rabbitTemplate.convertAndSend("amq.direct","direct",book);
}
/**
* 接收消息队列中的数据
*/
@Test
public void receiverMsg(){
Object obj = rabbitTemplate.receiveAndConvert("TESTQUEUE");
System.out.println(obj.getClass());
System.out.println(obj);
}
}