公司项目搜索部分用的elasticsearch,那么这两个之间的数据同步就是一个问题。

网上找了几个包,但都有各自的缺点,最后决定还是自己写一个脚本,大致思路如下:

1.在死循环中不断的select指定的表

2.读取表中更新时间晚于某个时间点的所有行 (初始化时候为"1970-01-01 00:00:00")

3.把需要的字段更新到elasticsearch

注意:1.中间要考虑到脚本中断,或者重启所以把最后的更新时间记录到了固定的txt文件

2.为了让脚本更加通用,不至于为了一个表就大幅度更改脚本,考虑动态生成变量,使用了locals和globals

代码如下:

#!/usr/bin/env python
# coding=utf-8
import sys
sys.path.append('/Users/cangyufu/work_jbkj/elabels-flask')
from modules.utils.commons import app, redispool, db_master, db_slave
from sqlalchemy import text
import os
import datetime
import time
from service.myelasticsearch.index import es
from modules.utils.mysqldb import db_obj_dict
import datetime CONST_SLEEP = 3 WORK_INDEX = 'test' #https://stackoverflow.com/questions/136168/get-last-n-lines-of-a-file-with-python-similar-to-tail
def tail(f, lines=1):
total_lines_wanted = lines BLOCK_SIZE = 1024
f.seek(0, 2)
block_end_byte = f.tell()
lines_to_go = total_lines_wanted
block_number = -1
blocks = [] # blocks of size BLOCK_SIZE, in reverse order starting
# from the end of the file
while lines_to_go > 0 and block_end_byte > 0:
if (block_end_byte - BLOCK_SIZE > 0):
# read the last block we haven't yet read
f.seek(block_number*BLOCK_SIZE, 2)
blocks.append(f.read(BLOCK_SIZE))
else:
# file too small, start from begining
f.seek(0,0)
# only read what was not read
blocks.append(f.read(block_end_byte))
lines_found = blocks[-1].count('\n')
lines_to_go -= lines_found
block_end_byte -= BLOCK_SIZE
block_number -= 1
all_read_text = ''.join(reversed(blocks))
return '\n'.join(all_read_text.splitlines()[-total_lines_wanted:]) def is_file_exists(filename):
if not os.path.isfile(filename):
file = open(filename, 'wb')
file.write("1970-01-01 00:00:00\n")
file.close() #传入要监控的表名
def sync_main(*args):
for table in args:
try:
callable(globals()['monitor_'+table])
except Exception:
raise Exception('lack function monitor_{}'.format(table))
for table in args:
filename = ''.join(['monitor_', table, '.txt'])
locals()[table+'path'] = os.path.join(os.path.dirname(__file__), filename)
is_file_exists(locals()[table+'path'])
locals()[table+'file'] = open(locals()[table+'path'], 'rb+')
try:
print "begin"
while True:
count = 0
for table in args:
print 'handleing '+table
last_time = tail(locals()[table+'file'], 1)
update_time = globals()['monitor_'+table](last_time)
print update_time
if update_time == last_time:
count += 1
continue
locals()[table + 'file'].write(update_time+'\n')
locals()[table + 'file'].flush()
if count == len(args):
time.sleep(CONST_SLEEP)
except Exception, e:
print e
raise e
finally:
for table in args:
locals()[table + 'file'].close() ########################################################################################################################
#
# 如果要监控哪个表,必须要实现 函数 monitor_table_name,比如要监控table1表,就必须要实现monitor_table1函数,
# 传入参数为开始更新的起始时间,初始化时候为1970-01-01 00:00:00,返回更新到的最新的时间
#
########################################################################################################################
def monitor_table1(last_time):
pass
return last_time
def monitor_table2(last_time):
pass
return last_time
def trans_date_time(dt): 
   return datetime.datetime.strptime(dt, "%Y-%m-%d %H:%M:%S") sync_main('table1','table2')

[同步脚本]mysql-elasticsearch同步的更多相关文章

  1. Mysql半同步复制模式说明及配置示例 - 运维小结

    MySQL主从复制包括异步模式.半同步模式.GTID模式以及多源复制模式,默认是异步模式 (如之前详细介绍的mysql主从复制).所谓异步模式指的是MySQL 主服务器上I/O thread 线程将二 ...

  2. MySQL主从同步原理

    mysql主从复制用途 实时灾备,用于故障切换 读写分离,提供查询服务 备份,避免影响业务 主从部署必要条件 主库开启binlo日志(设置log-bin参数) 主从server-id不同 从库可以连同 ...

  3. Elasticsearch和mysql数据同步(elasticsearch-jdbc)

    1.介绍 对mysql.oracle等数据库数据进行同步到ES有三种做法:一个是通过elasticsearch提供的API进行增删改查,一个就是通过中间件进行数据全量.增量的数据同步,另一个是通过收集 ...

  4. 监控mysql主从同步状态脚本

    监控mysql主从同步状态脚本 示例一: cat check_mysql_health #!/bin/sh slave_is=($(mysql -S /tmp/mysql3307.sock -uroo ...

  5. shell脚本修复MySQL主从同步

    发布:thebaby   来源:net     [大 中 小] 分享一例shell脚本,用于修改mysql的主从同步问题,有需要的朋友参考下吧. 一个可以修改mysql主从同步的shell脚本. 例子 ...

  6. elasticsearch -- Logstash实现mysql同步数据到elasticsearch

    配置 安装插件由于这里是从mysql同步数据到elasticsearch,所以需要安装jdbc的入插件和elasticsearch的出插件:logstash-input-jdbc.logstash-o ...

  7. nagios系列(七)nagios通过自定义脚本的方式监控mysql主从同步

    nagios监控mysql主从同步 起因:nagios可能监控到mysql服务的运行情况,但确不能监控mysql的主从复制是否正常:有时候,同步已经停止,但管理人员却不知道. 登陆mysql从服务器, ...

  8. Elasticsearch学习(2) windows环境下Elasticsearch同步mysql数据库

    在上一章中,我们已经能够通过spring boot来使用Elasticsearch,但是由于我们习惯性的将数据写入mysql,所以为了解决这个问题,Elasticsearch为我们提供了一个插件log ...

  9. shell脚本监控MySQL主从同步

    企业面试题1:监控MySQL主从同步是否异常,如果异常,则发送短信或者邮件给管理员. 阶段1:开发一个守护进程脚本每30秒实现检测一次. 阶段2:如果同步出现如下错误号(1158,1159,1008, ...

  10. 用shell脚本监控MySQL主从同步

    企业面试题1:(生产实战案例):监控MySQL主从同步是否异常,如果异常,则发送短信或者邮件给管理员.提示:如果没主从同步环境,可以用下面文本放到文件里读取来模拟:阶段1:开发一个守护进程脚本每30秒 ...

随机推荐

  1. android 系统开发板挂载U盘

    cat /proc/partitions 查看有u盘设备 df 查看挂载情况 iTOP4416开发板插入u盘,自动挂载到 /mnt/udisk1

  2. 深入理解JS this,作用域

    深入理解JS this 阮一峰博客链接http://www.ruanyifeng.com/blog/2010/04/using_this_keyword_in_javascript.html this ...

  3. Spark记录-SparkSQL

    Spark SQL的一个用途是执行SQL查询.Spark SQL也可以用来从现有的Hive安装中读取数据.有关如何配置此功能的更多信息,请参阅Hive表部分.从另一种编程语言中运行SQL时,结果将作为 ...

  4. Redis记录-Redis命令

    Redis命令是用于在Redis服务器上执行一些操作.要在Redis服务器上运行命令,需要一个Redis客户端.Redis客户端在Redis包中有提供,这个包在我们前面的安装教程中就有安装过了. 语法 ...

  5. WINDOWS控制界面操作命令for WIN10

    Windows系统:开始--运行--命令大全: cmd--------CMD命令提示符 cleanmgr-------垃圾整理 compmgmt.msc---计算机管理 conf----------- ...

  6. js 正则学习小记之匹配字符串字面量

    今天看了第5章几个例子,有点收获,记录下来当作回顾也当作分享. 关于匹配字符串问题,有很多种类型,今天讨论 js 代码里的字符串匹配.(因为我想学完之后写个语法高亮练手,所以用js代码当作例子) va ...

  7. html5 canvas创建阴影

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  8. 广度优先搜索(BFS)----------------(TjuOj1140_Dungeon Master)

    这次整理了一下广度优先搜索的框架,以后可以拿来直接用了.TjuOj1140是一个三维的迷宫题,在BFS时我增加了一个控制数组,用来对队列的出队进行控制,确保每次出队的结点均为同一步长的结点,个人认为比 ...

  9. Servlet笔记8--乱码解决方案

    乱码解决方案: 代码详解: package com.bjpowernode.javaweb.servlet; import java.io.IOException; import javax.serv ...

  10. 洛谷 P5206: bzoj 5475: LOJ 2983: [WC2019] 数树

    一道技巧性非常强的计数题,历年WC出得最好(同时可能是比较简单)的题目之一. 题目传送门:洛谷P5206. 题意简述: 给定 \(n, y\). 一张图有 \(|V| = n\) 个点.对于两棵树 \ ...