公司项目搜索部分用的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. SQL记录-PLSQL事务

    PL/SQL事务   数据库事务是一个工作的原子单元,其可以由一个或多个相关的SQL语句组成.所谓的原子性就是数据库的修改所带来的构成事务的SQL语句可以集体被提交,即永久到数据库或从数据库中(撤消) ...

  2. jquery的json对象与字符串之间转换

    json对象----- >>字符串 JSON.stringify(obj) json字符串------>>json对象 JSON.parse(string) 公众号 欢迎关注我 ...

  3. Matrix67|自由职业者,数学爱好者

    Matrix67|自由职业者,数学爱好者 介绍一下你自己和所做的工作. 我叫顾森,网名 Matrix67,长住北京的重庆人,目前没有固定的职业.一会儿当当码农,一会儿做做编辑,一会儿教教数学,一会儿写 ...

  4. TTPRequest 提示#import <libxml/HTMLparser.h>找不到 的解决方法

    本文永久地址为http://www.cnblogs.com/ChenYilong/p/3984251.html ,转载请注明出处. ASIHTTPRequest 或者AFNetwork提示的#impo ...

  5. Linux - awk 文本处理工具二

    awk 判断格式 awk '{print ($1>$2)?"第一排"$1:"第二排"$2}' # 条件判断 括号代表if语句判断 "?" ...

  6. shell tr命令

    tr 命令可以对来自标准输入的字符进行替换.压缩和删除. tr 指令从标准输入设备读取数据,经过字符串转译后,将结果输出到标准输出设备. tr 常用参数 -c # 用字符串1中字符集的补集替换此字符集 ...

  7. BurpSuite中的安全测试插件推荐

    Burp Suite 是用于攻击web 应用程序的集成平台.它包含了许多工具,并为这些工具设计了许多接口,以促进加快攻击应用程序的过程.所有的工具都共享一个能处理并显示HTTP 消息,持久性,认证,代 ...

  8. CSS之外边距折叠

    外边距折叠 Collapsing margins,即外边距折叠,指的是毗邻的两个或多个外边距 (margin) 会合并成一个外边距. 其中所说的 margin 毗邻,可以归结为以下两点: 这两个或多个 ...

  9. TcxGrid 调整列位置的事件

  10. Redis五种数据类型-设置key的过期时间

    1.redis命令客户端 [root@localhost bin]# ./redis-cli 127.0.0.1:6379> #是否运行着 127.0.0.1:6379> ping PON ...