zookeeper 负载mysql

 
 
1.mysql01

20.5.101.31_/root>cat agent.py 
import os
import time
import socket
from kazoo.client import KazooClient
from kazoo.client import KazooState
zk = KazooClient(hosts='20.5.101.15:12181',timeout=500,read_only=True)
zk.start()
# zk.delete('/scan/002')
if zk.exists('/mysql'):
    print "/mysql already exists"
elif zk.exists('/mysql/001'):
    zk.delete('/mysql/001')
else:
    zk.create('/mysql')
zk.create('/mysql/001',"20.5.101.31",ephemeral=True)
def check_port(ip,port):
    ip=ip
    print type(ip)
    port=port
    print ip
    print port
    print type(port)
    s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    s.settimeout(5)
    host=(ip,port)
    print host
    print  s.connect_ex(host)
    r=s.connect_ex(host)
    print '---------------'
    print r
    print type(r)
    print '---------------'
    if r==0:
       return 1
    else:
       zk.delete('/mysql/001')
       exit(0)
while True:
  time.sleep(5) 
  check_port('127.0.0.1',3306)

2.mysql02
[root@yyjk zookeeper]# cat agent.py 
import os
import time
import socket
from kazoo.client import KazooClient
from kazoo.client import KazooState
zk = KazooClient(hosts='20.5.101.15:12181',timeout=500,read_only=True)
zk.start()
# zk.delete('/scan/002')
if zk.exists('/mysql'):
      print "/mysql already exists"
elif zk.exists('/mysql/002'):
      zk.delete('/mysql/002')
else:
    zk.create('/mysql')
zk.create('/mysql/002',"10.5.100.232",ephemeral=True)
def check_port(ip,port):
    ip=ip
    print type(ip)
    port=port
    print ip
    print port
    print type(port)
    s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    s.settimeout(5)
    host=(ip,port)
    print host
    print  s.connect_ex(host)
    r=s.connect_ex(host)
    print '---------------'
    print r
    print type(r)
    print '---------------'
    if r==0:
       return 1
    else:
       zk.delete('/mysql/002')
       exit(0)
while True:
  time.sleep(5) 
  check_port('127.0.0.1',3306)



客服端使用:
from kazoo.client import KazooClient
from kazoo.client import KazooState

import time
print time.ctime()
import MySQLdb
zk = KazooClient(hosts='20.5.101.15:12181',timeout=500,read_only=True)
zk.start()
aa=zk.exists('/mysql/001')
print '--------------'
print aa
print '--------------'
if aa:
    ip=zk.get('/mysql/001')
    # print ip
else :
    ip=zk.get('/mysql/002')
print ip[0]

mysqlip=ip[0]

conn = MySQLdb.connect(
        host=mysqlip,
        port=3306,
        user='root',
        passwd='1234567',
        db='DEVOPS'
    )
cur = conn.cursor()
a = cur.execute("select * from test")
info = cur.fetchall()
d = {}
print info
print type(info)
time.sleep(2)
相关文章
相关标签/搜索