最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
Python实现各种中间件的连接代码示例
时间:2022-06-25 01:12:01 编辑:袖梨 来源:一聚教程网
本篇文章小编给大家分享一下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
相关文章
- 新三国志曹操传马超无双试炼四通关攻略 12-15
- 俄罗斯YANDEX引擎官网入口-免登录直达Yandex首页 12-15
- 漫蛙ManWa在线免费阅读入口_漫蛙ManWa官方网页版一键直达 12-15
- 逃离鸭科夫仓库区地窖在哪 仓库区地窖入口位置详情 12-15
- 光与影33号远征队熙艾尔bd玩法:熙艾尔毕业装备与加点思路介绍 12-15
- 漫蛙网页版免费入口进不去-漫蛙网页版最新免费版一键直达 12-15