Python實現各種中間件的連接

連接數據庫

Redis連接  

1、連接Redis單節點

import redis
"""
連接redis ConnectionPool 方式連接
"""
def connRedis(self):
    pool=redis.ConnectionPool(host='172.16.1.2',password='',db=2, port=6379) #按具體情況填寫參數
    r=redis.StrictRedis(connection_pool=pool)
    r.set("test_name","admin")
    print(r.get('test_name'))

2、連接Redis cluster集群 

python 操作redis 集群 用redis模塊不行,需要導入模塊

#!/usr/bin/env python
#coding:utf-8
 
 
from rediscluster import StrictRedisCluster
import sys
 
def redis_cluster():
    redis_nodes =  [{'host':'192.168.1.2','port':6378},
                    {'host':'192.168.1.2','port':6380},
                    {'host':'192.168.1.2','port':6381},
                    {'host':'192.168.1.2','port':6382},
                    {'host':'192.168.1.2','port':6383},
                    {'host':'192.168.1.2','port':6384},
                    {'host':'192.168.1.2','port':6385}
                   ]
    try:
        redisconn = StrictRedisCluster(startup_nodes=redis_nodes)
    except Exception,e:
        print "Connect Error!"
        sys.exit(1)
 
    redisconn.set('name','admin')
    print "name is: ", redisconn.get('name')
 
redis_cluster()

3、連接Redis哨兵集群

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import redis
from redis.sentinel import Sentinel
# 連接哨兵服務器(主機名也可以用域名)
sentinel = Sentinel([('172.31.0.2', 5001),
                     ('172.31.0.3', 5001),
                     ('172.31.0.4', 5001),
                     ('172.31.0.5', 5001)
             ],
                    socket_timeout=0.5)
# 獲取主服務器地址
master = sentinel.discover_master('mymaster')
print(master)
# 輸出:('172.31.0.2', 5001)
# 獲取從服務器地址
slave = sentinel.discover_slaves('mymaster')
print(slave)
# 輸出:[('172.31.3', 5001), ('172.31.0.4', 5001), ('172.31.0.5', 5001)]
# 獲取主服務器進行寫入
master = sentinel.master_for('mymaster', socket_timeout=0.5, password='redis_auth_pass', db=15)
w_ret = master.set('foo', 'bar')
# 輸出:True
# # 獲取從服務器進行讀取(默認是round-roubin)
slave = sentinel.slave_for('mymaster', socket_timeout=0.5, password='redis_auth_pass', db=15)
r_ret = slave.get('foo')
print(r_ret)
# # 輸出:bar

以上就是Python實現各種中間件的連接實現的詳細內容,更多關於Python連接中間件的資料請關註WalkonNet其它相關文章!

推薦閱讀: