MQ学习之实现商品的数据同步

本文介绍了一个电商系统中如何使用RabbitMQ进行消息传递。从后台系统的配置到前台系统及搜索系统的消息接收,详细阐述了消息队列在不同场景下的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、后台系统

1、导入依赖

<dependency>
	        <groupId>org.springframework.amqp</groupId>
	        <artifactId>spring-rabbit</artifactId>
	        <version>1.4.0.RELEASE</version>
	    </dependency>
	    <dependency>
			<groupId>com.rabbitmq</groupId>
			<artifactId>amqp-client</artifactId>
			<version>3.4.1</version>
		</dependency>

2、编写配置文件applicationContext-rabbitmq

<pre name="code" class="html"><beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:rabbit="http://www.springframework.org/schema/rabbit"
	xsi:schemaLocation="http://www.springframework.org/schema/rabbit
	http://www.springframework.org/schema/rabbit/spring-rabbit-1.4.xsd
	http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-4.1.xsd">

	<!-- 定义RabbitMQ的连接工厂 -->
	<rabbit:connection-factory id="connectionFactory"
		host="${rabbitmq.host}" port="${rabbitmq.port}" username="${rabbitmq.username}" password="${rabbitmq.password}"
		virtual-host="${rabbitmq.vhost}" />
	
	<!-- 定义交换机 -->
	<rabbit:topic-exchange name="taotao-item-exchange" auto-declare="true" durable="true">
		<!-- 选择采用手动绑定队列 -->
	</rabbit:topic-exchange>
	
	<!-- MQ的管理,包括队列、交换器等 -->
	<rabbit:admin connection-factory="connectionFactory"/>
	
	<!-- 定义模板 -->
	<rabbit:template id="template" connection-factory="connectionFactory" exchange="taotao-item-exchange"/>

</beans>



3、service

package com.taotao.manage.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.abel533.entity.Example;
import com.github.pagehelper.PageInfo;
import com.taotao.common.service.ApiService;
import com.taotao.manage.pojo.Item;
import com.taotao.manage.pojo.ItemDesc;
import com.taotao.manage.pojo.ItemParamItem;

@Service
public class ItemService extends BaseService<Item> {

    // 注意:事务的转播性
    @Autowired
    private ItemDescService itemDescService;

    @Autowired
    private ItemParamItemService itemParamItemService;

    @Value("${TAOTAO_WEB_URL}")
    private String TAOTAO_WEB_URL;
    
    @Autowired
    private ApiService apiService;
    
    @Autowired
    private RabbitTemplate rabbitTemplate;
    
    private static final ObjectMapper MAPPER = new ObjectMapper();

    /**
     * 新增商品
     * 
     * @param item
     * @param desc
     */
    public void saveItem(Item item, String desc, String itemParams) {

        item.setStatus(1);// 初始状态
        item.setId(null);// 强制id为null,考虑到安全性

        // 新增商品
        super.save(item);

        // 新增商品描述数据
        ItemDesc itemDesc = new ItemDesc();
        itemDesc.setItemDesc(desc);
        itemDesc.setItemId(item.getId());
        this.itemDescService.save(itemDesc);

        if (StringUtils.isNotEmpty(itemParams)) {// 不为空时创建数据
            ItemParamItem itemParamItem = new ItemParamItem();
            itemParamItem.setItemId(item.getId());
            itemParamItem.setParamData(itemParams);
            this.itemParamItemService.save(itemParamItem);
        }
        
        //发送商品新增的消息到RabbitMQ
        sendMsg(item.getId(), "insert");
    }

    public PageInfo<Item> queryItemList(Integer page, Integer rows) {
        Example example = new Example(Item.class);
        example.setOrderByClause("updated DESC");
        example.createCriteria().andNotEqualTo("status", 3);
        return super.queryPageListByExample(example, page, rows);
    }

    /**
     * 实现商品的逻辑删除
     * 
     * @param ids
     */
    public void updateByIds(List<Object> ids) {
        Example example = new Example(Item.class);
        example.createCriteria().andIn("id", ids);
        Item item = new Item();
        item.setStatus(3);// 更改状态为3,说明该商品已经被删除
        super.getMapper().updateByExampleSelective(item, example);
        
        for (Object object : ids) {
            //发送商品删除的消息到RabbitMQ
            sendMsg(Long.valueOf(object.toString()), "delete");
        }
    }

    public void updateItem(Item item, String desc, ItemParamItem itemParamItem) {
        // 强制设置不能被更新的字段为null
        item.setStatus(null);
        item.setCreated(null);
        // 更新商品数据
        super.updateSelective(item);

        // 更新商品描述数据
        ItemDesc itemDesc = new ItemDesc();
        itemDesc.setItemId(item.getId());
        itemDesc.setItemDesc(desc);
        this.itemDescService.updateSelective(itemDesc);

        if (null != itemParamItem) {
            // 更新规格参数
            this.itemParamItemService.updateSelective(itemParamItem);
        }

//        try {
//            // 通知其他系统商品已经更新
//            String url = TAOTAO_WEB_URL + "/item/cache/" + item.getId() + ".html";
//            this.apiService.doPost(url);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        
        //发送商品更新的消息到RabbitMQ
        sendMsg(item.getId(), "update");
    }
    
    private void sendMsg(Long itemId,String type){
        try {
            Map<String, Object> msg = new HashMap<String, Object>();
            msg.put("itemId", itemId);
            msg.put("type", type);
            msg.put("created", System.currentTimeMillis());
            this.rabbitTemplate.convertAndSend("item." + type, MAPPER.writeValueAsString(msg));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

4、rabbitmq.properties

rabbitmq.host=127.0.0.1
rabbitmq.port=5672
rabbitmq.username=taotao
rabbitmq.password=taotao
rabbitmq.vhost=/taotao
二、前台系统接收消息

1、导入同样的依赖

2、配置文件

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:rabbit="http://www.springframework.org/schema/rabbit"
	xsi:schemaLocation="http://www.springframework.org/schema/rabbit
	http://www.springframework.org/schema/rabbit/spring-rabbit-1.4.xsd
	http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-4.1.xsd">

	<!-- 定义RabbitMQ的连接工厂 -->
	<rabbit:connection-factory id="connectionFactory"
		host="${rabbitmq.host}" port="${rabbitmq.port}" username="${rabbitmq.username}" password="${rabbitmq.password}"
		virtual-host="${rabbitmq.vhost}" />
	
	<!-- MQ的管理,包括队列、交换器等 -->
	<rabbit:admin connection-factory="connectionFactory"/>
	
	<!-- 定义队列 -->
	<rabbit:queue name="taotao-web-item" auto-declare="true" durable="true"/>
	
	<!-- 设置监听 -->
	<rabbit:listener-container connection-factory="connectionFactory">
		<rabbit:listener ref="itemMQHandler" method="execute" queue-names="taotao-web-item"/>
	</rabbit:listener-container>

</beans>

3、rabbitmq.properties

rabbitmq.host=127.0.0.1
rabbitmq.port=5672
rabbitmq.username=taotao
rabbitmq.password=taotao
rabbitmq.vhost=/taotao
4、ItemMQHandler

package com.taotao.web.mq.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.taotao.common.service.RedisService;
import com.taotao.web.service.ItemService;

@Component
public class ItemMQHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(ItemMQHandler.class);

    private static final ObjectMapper MAPPER = new ObjectMapper();

    @Autowired
    private RedisService redisService;

    public void execute(String msg) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("接收到消息,MSG = {}", msg);
        }
        try {
            JsonNode jsonNode = MAPPER.readTree(msg);
            Long itemId = jsonNode.get("itemId").asLong();
            this.redisService.del(ItemService.REDIS_ITEM_KEY + itemId);
        } catch (Exception e) {
            LOGGER.error("处理消息出错! MSG = " + msg, e);
        }
    }

}
5、


三、搜索系统接收消息

1、导入同样的依赖

2、配置文件

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:rabbit="http://www.springframework.org/schema/rabbit"
	xsi:schemaLocation="http://www.springframework.org/schema/rabbit
	http://www.springframework.org/schema/rabbit/spring-rabbit-1.4.xsd
	http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-4.1.xsd">

	<!-- 定义RabbitMQ的连接工厂 -->
	<rabbit:connection-factory id="connectionFactory"
		host="${rabbitmq.host}" port="${rabbitmq.port}" username="${rabbitmq.username}" password="${rabbitmq.password}"
		virtual-host="${rabbitmq.vhost}" />
	
	<!-- MQ的管理,包括队列、交换器等 -->
	<rabbit:admin connection-factory="connectionFactory"/>
	
	<!-- 定义队列 -->
	<rabbit:queue name="taotao-search-item" auto-declare="true" durable="true"/>
	
	<!-- 设置监听 -->
	<rabbit:listener-container connection-factory="connectionFactory">
		<rabbit:listener ref="itemMQHandler" method="execute" queue-names="taotao-search-item"/>
	</rabbit:listener-container>

</beans>

3、同样的rabbitmq.properties文件

4、ItemMQHandler

package com.taotao.search.mq.handler;

import org.apache.commons.lang3.StringUtils;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.taotao.search.bean.Item;
import com.taotao.search.service.ItemService;

@Component
public class ItemMQHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(ItemMQHandler.class);

    private static final ObjectMapper MAPPER = new ObjectMapper();

    @Autowired
    private HttpSolrServer httpSolrServer;

    @Autowired
    private ItemService itemService;

    public void execute(String msg) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("接收到消息,MSG = {}", msg);
        }
        try {
            JsonNode jsonNode = MAPPER.readTree(msg);
            Long itemId = jsonNode.get("itemId").asLong();
            String type = jsonNode.get("type").asText();
            if (StringUtils.equals(type, "insert") || StringUtils.equals(type, "update")) {
                // 查询商品的数据
                Item item = this.itemService.queryItemById(itemId);
                this.httpSolrServer.addBean(item);

            } else if (StringUtils.equals(type, "delete")) {
                this.httpSolrServer.deleteById(String.valueOf(itemId));
            }
            // 提交
            this.httpSolrServer.commit();
        } catch (Exception e) {
            LOGGER.error("处理消息出错! MSG = " + msg, e);
        }
    }

}
5、ItemService

package com.taotao.search.service;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.taotao.search.bean.Item;

@Service
public class ItemService {

    @Autowired
    private ApiService apiService;

    @Value("${MANAGE_TAOTAO_URL}")
    private String MANAGE_TAOTAO_URL;

    private static final ObjectMapper MAPPER = new ObjectMapper();

    /**
     * 根据商品id查询商品数据
     * 
     * @param itemId
     * @return
     */
    public Item queryItemById(Long itemId) {
        String url = MANAGE_TAOTAO_URL + "/rest/item/" + itemId;
        try {
            String jsonData = this.apiService.doGet(url);
            if (StringUtils.isEmpty(jsonData)) {
                return null;
            }
            return MAPPER.readValue(jsonData, Item.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


}
6、rabbitmq.properties文件加上MANAGE_TAOTAO_URL=http://manage.taotao.com

7、ApiService、applicationContext-httpclient.xml、httpclient.properties复制过来,前面笔记有。

8、绑定





<think>好的,我现在需要帮助用户寻找适合的MySQL和Elasticsearch数据同步工具。首先,用户明确提到了需要工具推荐,所以我得先整理现有的常见工具,并比较它们的优缺点。 根据用户提供的引用内容,有三个主要的工具被提到:DataX、Canal和Logstash。我需要逐个分析这些工具的特点,适用场景,以及如何配置使用。另外,用户可能还关心实时性、配置复杂度、社区支持等方面。 首先看引用[3]提到的DataX。这是一个阿里巴巴的开源工具,支持批量同步,适合全量数据迁移。用户可能需要在初次同步时使用,或者定期全量更新。DataX的配置涉及mysqlreader和elasticsearchwriter,需要编写JSON作业配置文件。优点是稳定性高,适合大数据量,但缺点是实时性不足,因为是批处理。 然后是引用[1]和[2]中的Canal。Canal通过解析MySQL的binlog实现实时同步,这对需要实时搜索的应用非常关键,比如电商中的商品更新。Canal需要配置服务器和客户端,可能稍微复杂一些,但实时性好,适合增量同步。用户如果对延迟敏感,Canal会是一个好选择。不过,可能需要结合其他组件如MQ来提高可靠性,防止数据丢失。 接下来是Logstash,虽然用户没有直接提到,但Logstash是Elastic Stack的一部分,支持JDBC输入插件来定期轮询MySQL,然后输出到Elasticsearch。这种方式可以实现准实时同步,配置相对简单,适合中小规模的数据,但频繁的查询可能对MySQL有压力,尤其是数据量大的时候。 此外,还需要考虑其他可能的工具,比如Debezium,它也是一个基于CDC的工具,和Canal类似,但属于Apache项目,可能有更广泛的社区支持。不过用户没有提到,可能需要简要补充作为额外推荐。 用户可能需要根据具体场景选择工具:全量同步用DataX,实时增量用Canal或Debezium,简单定期同步用Logstash。同时,监控工具如Kibana和Prometheus也很重要,确保同步过程的可靠性。 最后,生成相关问题时要覆盖性能、优化、应用场景以及工具比较,帮助用户进一步探索。</think>以下是MySQL与Elasticsearch数据同步工具的推荐及技术特点分析: --- ### **一、主流工具推荐** #### **1. DataX(批量同步)** 阿里巴巴开源的异构数据源离线同步工具,通过配置JSON作业实现全量数据迁移。 - **优势**:支持百万级数据量、可视化配置、可扩展插件 - **配置示例**: ```json "job": { "content": [{ "reader": { "name": "mysqlreader", "parameter": { "username": "root", "password": "123456", "connection": [{ "querySql": "SELECT * FROM products" }] } }, "writer": { "name": "elasticsearchwriter", "parameter": { "endpoint": "http://localhost:9200", "index": "product_index" } } }] } ``` - **适用场景**:初次全量同步、周期性全量更新[^3] #### **2. Canal(实时同步)** 基于MySQL binlog解析的增量数据同步方案,实现毫秒级延迟。 - **核心流程**: 1. 部署Canal Server捕获binlog事件 2. 通过MQ(如Kafka)转发数据 3. 编写消费者写入Elasticsearch - **优势**:高实时性、低侵入性 - **典型应用**:电商价格实时更新、日志流处理[^1][^2] #### **3. Logstash(定时轮询)** Elastic官方工具,通过JDBC插件拉取数据。 - **配置示例**: ```ruby input { jdbc { jdbc_driver_library => "mysql-connector-java.jar" jdbc_connection_string => "jdbc:mysql://localhost:3306/db" jdbc_user => "root" jdbc_password => "123456" schedule => "*/5 * * * *" # 每5分钟同步 statement => "SELECT * FROM orders WHERE update_time > :sql_last_value" } } output { elasticsearch { hosts => ["http://localhost:9200"] index => "order_index" } } ``` - **适用场景**:中小规模数据、非强实时场景 --- ### **二、选型建议** | 工具 | 同步类型 | 延迟 | 数据量 | 学习成本 | |-----------|----------|--------|----------|----------| | DataX | 批量 | 高 | 百万级+ | 中等 | | Canal | 实时 | 毫秒级 | 无上限 | 较高 | | Logstash | 定时 | 分钟级 | 十万级 | 低 | **推荐组合**: - **实时搜索系统**:Canal + Kafka + Elasticsearch - **离线分析场景**:DataX(全量) + Logstash(增量) --- ### **三、监控与优化** - 使用Kibana监控Elasticsearch索引健康度 - 通过Prometheus采集同步延迟指标 - 优化建议: - 批量写入ES时设置`refresh_interval=-1` - MySQL侧增加索引加速查询 ---
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值