【SpringCloud+RabbitMQ+Docker+Redis+搜索+分布式,系统详解springcloud微服务技术栈课程|黑马程序员Java微服务】
案例:利用MQ实现mysql与elasticsearch数据同步
利用课前资料提供的hotel-admin项目作为酒店管理的微服务。当酒店数据发生增、删、改时,要求对elasticsearch中数据也要完成相同操作。

步骤:
【在hotel-admin 中】
拷贝hotel-demo 中常量类到admin 工程中
package cn.itcast.hotel.constants;/*** ClassName: MqConstants* date: 2022/11/3 16:48** @author DingJiaxiong*/public class MqConstants {//交换机public final static String HOTEL_EXCHANGE = "hotel.topic";//监听新增和修改的队列public final static String HOTEL_INSERT_QUEUE = "hotel.insert.queue";//监听删除的队列public final static String HOTEL_DELETE_QUEUE = "hotel.delete.queue";//新增或修改的RoutingKeypublic final static String HOTEL_INSERT_KEY = "hotel.insert";//删除的RoutingKeypublic final static String HOTEL_DELETE_KEY = "hotel.delete";}

OK
【引入amqp 依赖】
org.springframework.boot spring-boot-starter-amqp

记得刷一下
【修改配置文件】
rabbitmq:host: 118.195.243.105port: 5672username: itcastpassword: 123321virtual-host: /

【编写消息发送代码】
修改控制器
package cn.itcast.hotel.web;import cn.itcast.hotel.constants.MqConstants;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.PageResult;
import cn.itcast.hotel.service.IHotelService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;import java.security.InvalidParameterException;@RestController
@RequestMapping("hotel")
public class HotelController {@Autowiredprivate IHotelService hotelService;@Autowiredprivate RabbitTemplate rabbitTemplate;@GetMapping("/{id}")public Hotel queryById(@PathVariable("id") Long id){return hotelService.getById(id);}@GetMapping("/list")public PageResult hotelList(@RequestParam(value = "page", defaultValue = "1") Integer page,@RequestParam(value = "size", defaultValue = "1") Integer size){Page result = hotelService.page(new Page<>(page, size));return new PageResult(result.getTotal(), result.getRecords());}@PostMappingpublic void saveHotel(@RequestBody Hotel hotel){hotelService.save(hotel);//数据新增时,调用rabbittemplate,告诉hotel-demo,有数据发生新增了rabbitTemplate.convertAndSend(MqConstants.HOTEL_EXCHANGE,MqConstants.HOTEL_INSERT_KEY,hotel.getId());}@PutMapping()public void updateById(@RequestBody Hotel hotel){if (hotel.getId() == null) {throw new InvalidParameterException("id不能为空");}hotelService.updateById(hotel);//数据修改时,调用rabbittemplate,告诉hotel-demo,有数据发生修改了rabbitTemplate.convertAndSend(MqConstants.HOTEL_EXCHANGE,MqConstants.HOTEL_INSERT_KEY,hotel.getId());}@DeleteMapping("/{id}")public void deleteById(@PathVariable("id") Long id) {hotelService.removeById(id);//数据删除时,调用rabbittemplate,告诉hotel-demo,有数据发生删除了rabbitTemplate.convertAndSend(MqConstants.HOTEL_EXCHANGE,MqConstants.HOTEL_DELETE_KEY,id);}
}
根据key 将消息发送到不同的队列