Springboot 整合RabbitMQ和RabbitMQ的使用
1、登录到RabbitMQ界面,创建交换机
`
`
2、创建消息队列
`
`
3、交换机和消息队列进行绑定
`
`点进去
Virtual host设置为/
这样就绑定完了
========================================================================================
pom中引入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
配置文件
#RabbitMQ
spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
spring.rabbitmq.virtual-host=/
spring.rabbitmq.listener.simple.prefetch=10
spring.rabbitmq.listener.simple.acknowledge-mode=manual
写入
@Service
public class RabbitMqServiceImpl implements RabbitMqService {
@Autowired
private RabbitTemplate rabbitTemplate;
@Override
public String sendData2MQ(Long userId, Long seckillId) {
String orderNo = UUID.randomUUID().toString();
//2、将订单编号、用户ID保存到rabbitMQ中去
Map<String,Object> dataMap = new HashMap<>();
dataMap.put("orderNo",orderNo);
dataMap.put("userId",userId);
dataMap.put("seckillId",seckillId);
rabbitTemplate.convertAndSend("xcc.order",null,dataMap);
return orderNo;
}
}
@RestController
@RequestMapping("/rabbit")
public class RabbitMQController {
@Autowired
private RabbitMqService rabbitMqService;
@GetMapping("/put")
public Map<String,Object> start(Long userId,Long seckillId){
Map<String,Object> map = new HashMap<>();
String s = rabbitMqService.sendData2MQ(userId, seckillId);
map.put("ID",s);
return map;
}
}
数据已经插入进来了 。。。。。 如何取出数据呢,这块比较麻烦
package com.xccc.seckill.seckilll.controller;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.Map;
/**
* @author xuchangcheng
* @create 2019-11-05 15:05
* @desc 处理订单
*/
@Component
public class OrderHandle {
@RabbitListener(
bindings = @QueueBinding(
value = @Queue(value = "xcc.order.queue"),
exchange = @Exchange(value = "xcc.order",type = "fanout")
)
)
@RabbitHandler
public void handle(@Payload Map<String,Object> dataMap, Channel channel,@Headers Map<String,Object> headers){
try {
// 处理业务
System.out.println(dataMap);
//手动确认正确的从消息队列中取出数据,并且处理完毕
Long tag = (Long)headers.get(AmqpHeaders.DELIVERY_TAG);
channel.basicAck(tag,false);//消息队列确认
} catch (IOException e) {
e.printStackTrace();
}
}
}
`当Rabbit中有消息时,就会自动执行。。。。
————————————————
来源:csdn 原文链接:https://blog.csdn.net/xcc_2269861428/article/details/102915558
需要《深入实践springboot.pdf》资料,私信“资料”获取