引入依賴:
<dependency><groupId>org.springframework.amqp</groupId><artifactId>spring-rabbit-test</artifactId><scope>test</scope></dependency>
配置application.yml?
server:port: 8082
spring:rabbitmq:host: 192.168.37.105port: 5672username: adminpassword: adminvirtual-host: /shop:exchange: shop.exchange.directqueue: shop.queueroutingKey: shop.routingKey
?編寫配置類消息轉化器:
@Configuration
public class RabbitmqConfig {/*** 消息轉化器* 將對象轉化為 Json 字符串*/@Beanpublic MessageConverter messageConverter(){return new Jackson2JsonMessageConverter();}
}
創建生產者:
@RestController
@RequiredArgsConstructor
@RequestMapping("producer03")
public class Producer03Controller {private final RabbitTemplate rabbitTemplate;@GetMapping("/send01")public String sendMsgFanout(){rabbitTemplate.convertAndSend("exchange2.fanout","",new Student(2,"Alice","178",20));return "Producer02==>發送成功!";}@GetMapping("/send02")public String sendFanout(){rabbitTemplate.convertAndSend("exchange2.fanout","","Fanout發送消息!");return "Producer02==>發送成功!";}@GetMapping("/send03")public String sendMsgDirect(){rabbitTemplate.convertAndSend("exchange2.DIRECT","monian",new Student(2,"Alice","178",20));return "Producer02==>發送成功!";}@GetMapping("/send04")public String sendMsgDirectMsg(){rabbitTemplate.convertAndSend("exchange2.DIRECT","monian","發送的數據Direct!");return "Producer02==>發送成功!";}
}
創建消費者:
@Component
public class MsgListener02 {/*** 使用注解的方式,對交換機和隊列進行裝配* 如果存在就不創建** @param msg*/@RabbitListener(bindings = @QueueBinding(value = @Queue(value = "queue02"),exchange = @Exchange(value = "exchange2.fanout", type = ExchangeTypes.FANOUT)))public void readMsg(Student stu) {System.out.println("annotationListener::Fanout => :" + stu);}@RabbitListener(bindings = @QueueBinding(value = @Queue(value = "queue02"),exchange = @Exchange(value = "exchange2.fanout", type = ExchangeTypes.FANOUT)))public void readMsg(String msg) {System.out.println("annotationListener::Fanout => :" + msg);}@RabbitListener(bindings = @QueueBinding(value = @Queue(value = "queue03"),exchange = @Exchange(value = "exchange2.DIRECT", type = ExchangeTypes.DIRECT),key = "monian"))public void readMsgDirect(Student stu) {System.out.println("annotationListener::Direct => :" + stu);}@RabbitListener(bindings = @QueueBinding(value = @Queue(value = "queue03"),exchange = @Exchange(value = "exchange2.DIRECT", type = ExchangeTypes.DIRECT),key = "monian"))public void readMsgDirect(String msg) {System.out.println("annotationListener::Direct => :" + msg);}}
編寫Student:
@AllArgsConstructor
@NoArgsConstructor
@Data
public class Student implements Serializable {private Integer id;private String name;private String phone;private Integer age;
}
測試結果:?