HM-SpringCloud微服务系列7.3【数据同步】

1 数据同步问题

elasticsearch中的酒店数据来自于mysql数据库,因此mysql数据发生改变时,elasticsearch也必须跟着改变,这个就是elasticsearch与mysql之间的数据同步
image

2 数据同步解决方案

  1. 常见的数据同步方案有三种:
    • 同步调用
    • 异步通知
    • 监听binlog
  2. 三种方案的优缺点与选择
    1. 方式一:同步调用
      • 优点:实现简单,粗暴
      • 缺点:业务耦合度高
    2. 方式二:异步通知
      • 优点:低耦合,实现难度一般
      • 缺点:依赖mq的可靠性
    3. 方式三:监听binlog
      • 优点:完全解除服务间耦合
      • 缺点:开启binlog增加数据库负担、实现复杂度高

2.1 同步调用

image
流程如下:

  • hotel-demo对外提供接口,用来修改elasticsearch中的数据
  • 酒店管理服务在完成数据库操作后,直接调用hotel-demo提供的接口

2.2 异步通知

image
流程如下:

  • hotel-admin对mysql数据库数据完成增、删、改后,发送MQ消息
  • hotel-demo监听MQ,接收到消息后完成elasticsearch数据修改

2.3 监听binlog

image
流程如下:

  • 给mysql开启binlog功能
  • mysql完成增、删、改操作都会记录在binlog中
  • hotel-demo基于canal监听binlog变化,实时更新elasticsearch中的内容

3 实现elasticsearch与数据库数据同步

3.1 案例思路

  • 利用课前资料提供的hotel-admin项目作为酒店管理的微服务。当酒店数据发生增、删、改时,要求对elasticsearch中数据也要完成相同操作。
  • 步骤:
    • 导入课前资料提供的hotel-admin项目,启动并测试酒店数据的CRUD
    • 声明exchange、queue、RoutingKey
    • 在hotel-admin中的增、删、改业务中完成消息发送
    • 在hotel-demo中完成消息监听,并更新elasticsearch中数据
    • 启动并测试数据同步功能

3.2 导入初始项目demo

导入
image
image
demo中已经包含了酒店的基本CRUD功能
image
修改
image
image
启动
image
访问
image
测试CRUD
image
image

3.3 声明交换机&队列

  • MQ结构如图:
    image

3.3.1 引入MQ依赖

在hotel-admin、hotel-demo中引入rabbitmq的依赖:

<!--amqp-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-amqp</artifactId>
</dependency>

image
image

3.3.2 yaml配置MQ

在hotel-admin和hotel-demo的application.yaml中配置rabbitmq

spring:
  rabbitmq:
    host: 192.168.2.109
    port: 5672
    username: yubaby
    password: 123321
    virtual-host: /

image
image

3.3.3 声明队列交换机名称

在hotel-admin和hotel-demo中的constatnts包下新建一个类MQConstants

package com.yppah.hoteldemo.constants;

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";
}

image
image

3.3.4 声明队列交换机

在hotel-demo中,定义配置类MQConfig,声明队列、交换机:

package com.yppah.hoteldemo.config;

import com.yppah.hoteldemo.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;

@Configuration
public class MQConfig {
    /**
     * 声明交换机
     * @return
     */
    @Bean
    public TopicExchange topicExchange() {
        return new TopicExchange(MQConstants.HOTEL_EXCHANGE, true, false);
    }
    /**
     * 声明插入队列
     * @return
     */
    @Bean
    public Queue insertQueue() {
        return new Queue(MQConstants.HOTEL_INSERT_QUEUE, true);
    }
    /**
     * 声明删除队列
     * @return
     */
    @Bean
    public Queue deleteQueue() {
        return new Queue(MQConstants.HOTEL_DELETE_QUEUE, true);
    }
    /**
     * 绑定插入队列到交换机
     * @return
     */
    @Bean
    public Binding insertQueueBinding() {
        return BindingBuilder.bind(insertQueue()).to(topicExchange()).with(MQConstants.HOTEL_INSERT_KEY);
    }
    /**
     * 绑定删除队列到交换机
     * @return
     */
    @Bean
    public Binding deleteQueueBinding() {
        return BindingBuilder.bind(deleteQueue()).to(topicExchange()).with(MQConstants.HOTEL_DELETE_KEY);
    }
}

image

3.4 发送MQ消息

在hotel-admin中的增、删、改业务中分别发送MQ消息:
image
image

点击查看代码
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 {

    @Autowired
    private IHotelService hotelService;

    @Autowired
    private 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<Hotel> result = hotelService.page(new Page<>(page, size));
        return new PageResult(result.getTotal(), result.getRecords());
    }

    @PostMapping
    public void saveHotel(@RequestBody Hotel hotel){
        hotelService.save(hotel);
        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.convertAndSend(MQConstants.HOTEL_EXCHANGE, MQConstants.HOTEL_INSERT_KEY, hotel.getId());
    }

    @DeleteMapping("/{id}")
    public void deleteById(@PathVariable("id") Long id) {
        hotelService.removeById(id);
        rabbitTemplate.convertAndSend(MQConstants.HOTEL_EXCHANGE, MQConstants.HOTEL_DELETE_KEY, id);
    }
}

3.5 接收MQ消息

hotel-demo接收到MQ消息要做的事情包括:

  • 新增消息:根据传递的hotel的id查询hotel信息,然后新增一条数据到索引库
  • 删除消息:根据传递的hotel的id删除索引库中的一条数据

3.5.1 接口新增业务声明

image

3.5.2 实现类实现业务

image

    // 参考HotelDocumentTest的testAddDocument()
    @Override
    public void insertById(Long id) {
        try {
            // 0. 根据id查询酒店数据
            Hotel hotel = getById(id);
            // 0.1 转换为HotelDoc
            HotelDoc hotelDoc = new HotelDoc(hotel);
            // 0.2 转JSON
            String json = JSON.toJSONString(hotelDoc);

            // 1.准备Request
            IndexRequest request = new IndexRequest("hotel").id(hotelDoc.getId().toString());
            // 2.准备请求参数DSL,其实就是文档的JSON字符串
            request.source(json, XContentType.JSON);
            // 3.发送请求
            client.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    // 参考HotelDocumentTest的testDeleteDocumentById()
    @Override
    public void deleteById(Long id) {
        try {
            // 1.准备Request
            DeleteRequest request = new DeleteRequest("hotel", id.toString());
            // 2.发送请求
            client.delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

3.5.3 编写监听器

image

package com.yppah.hoteldemo.mq;

import com.yppah.hoteldemo.constants.MQConstants;
import com.yppah.hoteldemo.service.IHotelService;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class HotelListener {

    @Autowired
    private IHotelService hotelService;

    /**
     * 监听酒店新增或修改数据
     * @param id
     */
    @RabbitListener(queues = MQConstants.HOTEL_INSERT_QUEUE)
    public void listenerHotelInsertOrUpdate(Long id) {
        hotelService.insertById(id);
    }

    /**
     * 监听酒店删除数据
     * @param id
     */
    @RabbitListener(queues = MQConstants.HOTEL_DELETE_QUEUE)
    public void listenerHotelDelete(Long id) {
        hotelService.deleteById(id);
    }
}

3.6 测试数据同步功能

3.6.1

启动centos虚拟机中docker的mq服务
image
访问http://10.193.193.141:15672/而不是http://192.168.2.109:15672/测试
image
image

特别注意
image
image
image

重启消息接收方hoteldemo服务
image
重启消息发送方hotel-admin服务
image
刷新MQ后台管理界面查看
image
image
image

3.6.2

需求:先修改某酒店的价格查看数据同步效果,然后删除该酒店数据查看效果,最后新增回该酒店数据查看效果

  1. 更新数据

image
image
image
image
image
image
image

  1. 删除数据
    image
    image
    image
    image
    image
    image

  2. 新增数据
    image
    image
    image
    image
    image
    image

至此,增删改均已实现ES与MYSQL的数据同步

posted @   yub4by  阅读(130)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示