Use redis implement a program or service availability

Use redis implement a program or service availability, a program or service is to be deployed on different servers, or deploy across the room, when the server is running a service hung up the service on another server can immediately on top here I simply redis use for this purpose.

The idea is: the same service deployed on different servers, every period of time under investigation a certain key (their definition) on redis to, if the key does not exist, the value of the key is provided, it may be an IP their present server, and a set time expired, and then perform the business logic of the service, if the key exists, the value of the key is not to see their own IP, if so, update the key expiration time. code show as below:

# coding:utf8
import time
import redis
import threading


REDIS_DB = {
    'host': '*********',
    'port': *****,
    'password': None,
}
KEY = "********"
EXPIRATION_TIME = 12
LOOP_TIME = 10
SERVER_IP = "1.1.1.1"


def use_redis(option=REDIS_DB):
    pool = redis.ConnectionPool(**option)
    r = redis.Redis(connection_pool=pool)
    return r


def get_key_from_redis():
    client = use_redis()
    flag = client.exists(KEY)
    if not flag:
        client.setex(KEY, SERVER_IP, EXPIRATION_TIME)
        t = threading.Thread(target=work)
        t.start()
    else:
        value = client.get(KEY)
        if value == SERVER_IP:
            client.expire(KEY, EXPIRATION_TIME)


# Business logic simulation
DEF Work (): the while True: .......... time.sleep(8) if __name__ == "__main__": while True: get_key_from_redis() time.sleep(LOOP_TIME)

Of course, every other period of time to check redis, this time than the key expiration time shorter.

Guess you like

Origin www.cnblogs.com/lucky-heng/p/11135410.html