Created
January 25, 2018 05:10
-
-
Save charsyam/dec9ad57cf805cc2a6d7f74dcb7fb9df to your computer and use it in GitHub Desktop.
backend_app04.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from flask import Flask | |
import redis | |
import kazoo | |
app = Flask(__name__) | |
from kazoo.client import KazooClient | |
import logging | |
zk = KazooClient(hosts='127.0.0.1:2181') | |
zk.start() | |
REDIS_NODE_PATH="/backend/caches/redis" | |
redis_conns = [] | |
def rebuild_redis_connections(children): | |
global redis_conns | |
tmp_redis_conns = [] | |
for child in children: | |
try: | |
value = zk.get(REDIS_NODE_PATH + "/" + child)[0].decode("utf-8") | |
v = value.split(':') | |
r = redis.StrictRedis(v[0], v[1]) | |
tmp_redis_conns.append(r) | |
except: | |
print(child) | |
redis_conns = tmp_redis_conns | |
print("rebuild " + str(redis_conns)) | |
def redis_watch_func(children): | |
create_redis_connections() | |
def watch_redis_node(): | |
children = zk.get_children(REDIS_NODE_PATH, watch=redis_watch_func) | |
def create_redis_connections(): | |
children = zk.get_children(REDIS_NODE_PATH) | |
rebuild_redis_connections(children) | |
watch_redis_node() | |
create_redis_connections() | |
def get_index(name): | |
s = 0 | |
for i in name: | |
s += ord(i) | |
return s % len(redis_conns) | |
@app.route('/<name>') | |
def hello_world(name): | |
idx = get_index(name) | |
rconn = redis_conns[idx] | |
v = rconn.incr(name) | |
return "Hello, {name}!, visit count = {count}".format(name=name, count=v) | |
@app.route('/lists') | |
def lists(): | |
v = [conn.connection_pool.get_connection("").port for conn in redis_conns] | |
return str(v) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment