补充:es与mysql之间的数据同步 2

本片文章只是对之前写的文章的补充,

es与mysql之间的数据同步

http://t.csdn.cn/npHt4

补充一:

之前的文章对于交换机、队列、绑定,使用的是@bean,

而这里使用的是纯注解版

在消费方,声明交换机:

package com.hmall.search.mq;

import com.hmall.search.service.IsearchService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.yaml.snakeyaml.events.Event;

/**
 * @author ning
 * @since 2022/12/12 0:16
 */

@Slf4j
@Component
public class ItemListener {

    @Autowired
    private IsearchService isearchService;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "up.queue"),//声明队列
            exchange = @Exchange(name = "item.topic",type = ExchangeTypes.TOPIC),//声明交换机
            key = "item.up"//声明绑定关系
    ))
    private void listenItemUp(Long id){
        log.info("监听到上架消息:"+ id);
        isearchService.saveitById(id);
    }

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "down.queue"),
            exchange = @Exchange(name = "item.topic",type = ExchangeTypes.TOPIC),
            key = "item.down"
    ))
    private void listenItemDown(Long id){
        log.info("监听到下架消息:"+ id);
        isearchService.deleteItemById(id);
    }

}

补充二:

之前的文章是直接使用es操作数据,新增和修改,这样做不是很合适,而且没有遵守单一原则,所以这里使用feign远程调用其他模块的接口方法,

1、新建一个feign模块(如果没有的话)

可以参考

http://t.csdn.cn/GqMVN

2、在模块中新建一个接口ItemClient(使用哪个模块就用哪个模块名+Client),在模块中定义你要在es中调用的方法,(也就是es需要操作数据库,但是其他模块已经写完的方法,就不需要再写一遍了)

例如:需要根据id查询数据库,就把其他模块写完的根据id查询数据库的方法写到接口里

package com.hmall.client;

import com.hmall.common.dto.Item;
import com.hmall.common.dto.PageDTO;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * 商品模块的远程调用
 *
 * @author ning
 * @since 2022/12/9 18:39
 */
//表示对应的是itemservice服务器
@FeignClient("itemservice")
public interface ItemClient {

    //分页查询
    @GetMapping("/item/list")
    public PageDTO<Item> list(@RequestParam("page") Integer page, @RequestParam("size") Integer size);

    //根据id查询数据
    @GetMapping("/item/{id}")
    public Item selectById(@PathVariable("id") Long id);
}

以上接口中还有分页查询的内容,详情可以参考

使用分页导入的方式把大量数据从mysql导入es

http://t.csdn.cn/XECXD

3、生产方和消费方的代码,只有消费方新增的代码有一点不同,其他的都一样

    //注入es的工具类
    @Autowired
    private RestHighLevelClient client;
    //注入feign远程调用的接口
    @Autowired
    private ItemClient itemClient;

    @Override
    public void saveitById(Long id) {
        try {
            //使用feign的远程调用接口,查询数据库
            //查询一条商品数据,并转为json
            Item item = itemClient.selectById(id);
            ItemDoc itemDoc = new ItemDoc(item);
            String jsonString = JSON.toJSONString(itemDoc);

            //创建请求
            IndexRequest request = new IndexRequest("item").id(id.toString());
            //设置参数
            request.source(jsonString, XContentType.JSON);
            //执行请求
            client.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要实现 ElasticsearchMySQL 数据保持同步,你可以按照以下步骤进行: 1. 安装 Elasticsearch:你需要在本地或服务器上安装 Elasticsearch,并启动它。你可以从官方网站下载并安装 Elasticsearch。 2. 安装 Elasticsearch JDBC 插件:你需要安装 Elasticsearch JDBC 插件,以便能够连接到 MySQL 数据库。你可以从 Elasticsearch 官网下载并安装插件。 3. 创建 Logstash 配置文件:你需要创建 Logstash 配置文件,以便将 MySQL 数据库中的数据同步Elasticsearch。以下是一个示例配置文件: ``` input { jdbc { jdbc_driver_library => "/path/to/mysql-connector-java.jar" jdbc_driver_class => "com.mysql.jdbc.Driver" jdbc_connection_string => "jdbc:mysql://localhost:3306/mydatabase" jdbc_user => "myuser" jdbc_password => "mypassword" schedule => "* * * * *" statement => "SELECT * from mytable where updated_at > :sql_last_value" use_column_value => true tracking_column => "updated_at" tracking_column_type => "timestamp" clean_run => true } } output { elasticsearch { hosts => ["localhost:9200"] index => "myindex" document_id => "%{id}" } } ``` 以上配置文件会每分钟查询一次 MySQL 数据库中的数据,并将其同步Elasticsearch 中。Logstash 会根据更新时间字段(这里是 updated_at)来判断哪些数据需要同步。如果你需要同步新增的数据,可以将 clean_run 参数设置为 false。 4. 启动 Logstash:使用以上配置文件启动 Logstash。 5. 验证同步结果:你可以使用 Elasticsearch 查询 API 验证同步结果。以下是一个示例查询: ```php require 'vendor/autoload.php'; $client = Elasticsearch\ClientBuilder::create()->build(); $params = [ 'index' => 'myindex', 'type' => 'mytype', 'body' => [ 'query' => [ 'match' => [ 'title' => 'php' ] ] ] ]; $response = $client->search($params); foreach ($response['hits']['hits'] as $hit) { echo $hit['_source']['title'] . "\n"; } ``` 以上是使用 Elasticsearch JDBC 插件实现 ElasticsearchMySQL 数据保持同步的基本步骤。你可以根据自己的需求进行调整和优化。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值