springboot1.5.4+rabbitMQ
前提:可以通过docker在vm虚拟机上生成镜像容器,非常便捷
- pom
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
- 配置
spring.rabbitmq.host=172.96.92.188 ---vm虚拟机地址
spring.rabbitmq.port=5672 --rabbitmq端口
spring.rabbitmq.username=admin ---mq新建的User,没用原来的guest
spring.rabbitmq.password=123456 --密码
spring.rabbitmq.virtual-host=/ -vhost
- JUnit-demo
3.1生成者——将消息发布到MQ
@Autowired
AmqpTemplate template;
//传入对象或者string
@Test
public void testSend(){
Video video = new Video();
video.setId(1);
video.setTitle("www");
template.convertAndSend("queue1",video);
}
3.2 消费者
@Component
public class MQconsumer{
@RabbitListener(queues = "queue1")
public void process(Video video) {
System.err.println("Receiver : " + JsonUtil.toJson(video));
}
}
3.3启动消费者应用,再启动junit单元测试发布消息,消费者应用会在控制台打印消息;
4. 项目中应用
4.1 生成者
@Autowired
private AmqpTemplate rabbitTemplate;
@GetMapping("add")
public CommonResp<Boolean> saveOrder(
@RequestParam(value = "video_id",required = true)int videoId,
HttpServletRequest request
){
String ipAddr = IpUtils.getIpAddr(request);
VideoOrderDto videoOrderDto = new VideoOrderDto();
videoOrderDto.setIp(ipAddr);
videoOrderDto.setUserId(1);
videoOrderDto.setVideoId(videoId);
rabbitTemplate.convertAndSend("queue1", videoOrderDto);
//假装一定会成功;
return new CommonResp<Boolean>(true,true);
}
4.2 消费者
@Component
public class MQconsumer{
@Autowired
private VideoOrderService videoOrderService;//实际处理服务的接口
@RabbitListener(queues = "queue1")
public void process(VideoOrderDto videoOrderDto) {
System.err.println("Receiver : " + JsonUtil.toJson(videoOrderDto));
Integer integer = videoOrderService.save(videoOrderDto);
if(integer==-1||integer==null){
System.err.println("新增失败");
}
System.err.println("mq处理完毕 ");
}
}```