微服务框架
【SpringCloud+RabbitMQ+Docker+Redis+搜索+分布式,系统详解springcloud微服务技术栈课程|黑马程序员Java微服务】
SpringCloud微服务架构
文章目录
- 微服务框架
- SpringCloud微服务架构
- 28 数据同步
- 28.3 声明队列和交换机
- 28.3.1 直接开干
 
 
 
 
28 数据同步
28.3 声明队列和交换机
28.3.1 直接开干
案例:利用MQ实现mysql与elasticsearch数据同步
利用课前资料提供的hotel-admin项目作为酒店管理的微服务。当酒店数据发生增、删、改时,要求对elasticsearch中数据也要完成相同操作。

步骤:
- 导入课前资料提供的hotel-admin项目,启动并测试酒店数据的CRUD √
- 声明exchange、queue、RoutingKey【这一步】
- 在hotel-admin中的增、删、改业务中完成消息发送
- 在hotel-demo中完成消息监听,并更新elasticsearch中数据
- 启动并测试数据同步功能
【在hotel-demo 中】
添加依赖
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-amqp</artifactId>
</dependency>

记得刷一下
【配置MQ】
先把RabbitMQ 跑起来

编写配置文件
rabbitmq:
  host: 118.195.246.137
  port: 5672
  username: itcast
  password: 123321
  virtual-host: /

OK
【声明队列交换机】
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";
    //新增或修改的RoutingKey
    public final static String HOTEL_INSERT_KEY = "hotel.insert";
    //删除的RoutingKey
    public final static String HOTEL_DELETE_KEY = "hotel.delete";
}
【绑定】
package cn.itcast.hotel.config;
import cn.itcast.hotel.constants.MqConstants;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
 * ClassName: MqConfig
 * date: 2022/11/3 16:55
 *
 * @author DingJiaxiong
 */
@Configuration
public class MqConfig {
    //交换机
    @Bean
    public TopicExchange topicExchange(){
        return new TopicExchange(MqConstants.HOTEL_EXCHANGE,true,false);
    }
    //两个队列
    //新增或修改
    @Bean
    public Queue insertQueue(){
        return new Queue(MqConstants.HOTEL_INSERT_QUEUE,true);
    }
    //删除
    @Bean
    public Queue deleteQueue(){
        return new Queue(MqConstants.HOTEL_DELETE_QUEUE,true);
    }
    //绑定关系
    @Bean
    public Binding insertQueueBinding(){
        return BindingBuilder.bind(insertQueue()).to(topicExchange()).with(MqConstants.HOTEL_INSERT_KEY);
    }
    @Bean
    public Binding deleteQueueBinding(){
        return BindingBuilder.bind(deleteQueue()).to(topicExchange()).with(MqConstants.HOTEL_DELETE_KEY);
    }
}
OK,这样就绑定好了














![[synchronized ]关键字详解](https://img-blog.csdnimg.cn/0e28df8c50aa4105809c4c89b1ec1971.png)




