公司项目搜索部分用的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. webpack打包提取css到独立文件

    将本来镶嵌在bundle.js的css转到外面来,我们需要用到一个插件:extract-text-webpack-plugin 使用方法: 1.安装 npm i extract-text-webpac ...

  2. Sql Server数据库小知识点总结

    把我在开发时候遇到的一点小知识持续更新在这里~ 1.where条件时常变 where UserID='1' 这里的UserID呢,它的值是经常在变化的,有时候要查2,有时候要查3的,有时候要查全部人! ...

  3. cin,cout,printf,scanf效率对比

    From:http://www.cnblogs.com/killerlegend/p/3918452.html Author:KillerLegend Date:2014.8.17 杭电OJ之3233 ...

  4. Spring Cloud(十四)Config 配置中心与客户端的使用与详细

    前言 在上一篇 文章 中我们直接用了本应在本文中配置的Config Server,对Config也有了一个基本的认识,即 Spring Cloud Config 是一种用来动态获取Git.SVN.本地 ...

  5. LINQ 查询

    概述 事实上,对于LINQ to Objects来说,就是通过为IEnumerable<T>接口定义了一组约50个扩展方式来实现的. Lambda表达式(拉姆达表达式,Lambda Exp ...

  6. Spring Boot实战系列-----------邮件发送

    快速导航 添加Maven依赖 配置文件增加邮箱相关配置 Service.Test项目代码构建 五种邮件发送类型讲解 文本邮件 html邮件 附件邮件 html内嵌图片邮件 模板邮件 问题汇总 添加ma ...

  7. Strange Queries(莫队)

    题目 You are given an array with n integers a1, a2, ..., an, and q queries to answer. Each query consi ...

  8. 爬虫笔记之w3cschool注册页面滑块验证码破解(巨简单滑块位置识别,非鼠标模拟轨迹)

    一.背景介绍 最开始接触验证码破解的时候就是破解的w3cschool的使用手机号找回密码页面的验证码,详见:验证码识别之w3cschool字符图片验证码(easy级别),这次破解一下他们注册页面的滑块 ...

  9. lucene入门查询索引——(三)

    1.用户接口(lucene不提供)

  10. Java基本数据类型装箱的127临界点

    package wrapper.demo; public class WrapperDemo { /** * @param args */ public static void main(String ...