公司项目搜索部分用的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. Docker:搭建私有仓库(Registry 2.4)

    一.背景 首先,Docker Hub是一个很好的用于管理公共镜像的地方,我们可以在上面找到想要的镜像(Docker Hub的下载量已经达到数亿次):而且我们也可以把自己的镜像推送上去.但是,有的时候, ...

  2. OpenStack中MySQL高可用配置

    采用Heartbeat+DRBD+mysql高可用方案,配置两个节点的高可用集群 l  配置各节点互相解析 gb07 gb06 l  配置各节点时间同步 gb07 [root@gb07 ~]# ntp ...

  3. C语言复习---用筛选法求100之内的素数

    #include <stdio.h> #include <stdlib.h> #include <math.h> int main() { int i, j; ] ...

  4. Solr记录-solr内核与索引

    Solr核心(内核) Solr核心(Core)是Lucene索引的运行实例,包含使用它所需的所有Solr配置文件.我们需要创建一个Solr Core来执行索引和分析等操作. Solr应用程序可以包含一 ...

  5. IDEA启动Tomcat报错1099 is already in use

    IDEA中启动Tomcat报错,Error running Tomcat7.0.52: Address localhost:1099 is already in use 或者是 java.rmi.se ...

  6. 何凯文每日一句||DAY10

  7. python学习笔记6--操作redis

    一.redis操作 import redis r=redis.Redis(host='211.149.218.16',port=6379,password='123456',db=2) r.set(' ...

  8. mac 无法验证副本

    转: 这个是拆机后断了电源,导致时间不对,也就是说现在电脑的时间比U盘制作的时间还早,所以有这样的错误提示. 在终端里面修改时间请参考下面的代码,按回车键确认:date 062614102014.30 ...

  9. Android利用LocalSocket实现Java端进程与C端进程之间的IPC

    Android是建立在Linux之上的OS,在涉及到安全.网络协议.文件加密等功能时,往往需要通过C语言调用底层API来实现,而如何发出指令让C端执行我们想要的功能,并且在执行之后有返回结果呢,这就需 ...

  10. iframe引入网页

    <!DOCTYPE html> <html> <body> <iframe src="/example/html/demo_iframe.html& ...