使用with打开文件的方式,是调用了上下文管理的功能

 #打开文件的两种方法:

 f = open('a.txt','r')

 with open('a.txt','r') as f 

 实现使用with关闭socket
import contextlib
import socket @contextlib.contextmanage
def Sock(ip,port):
socket = socket.socket()
socket.bind((ip,port))
socket.listen(5)
try:
yield socket
finally:
socket.close() #执行Sock函数传入参数,执行到yield socket返回值给s,执行with语句体,执行finally后面的语句
with Sock('127.0.0.1',8000) as s:
print(s)

redis的发布订阅

class RedisHelper:

    def __init__(self):
#调用类时自动连接redis
self.__conn = redis.Redis(host='192.168.1.100') def public(self, msg, chan):
self.__conn.publish(chan, msg)
return True def subscribe(self, chan):
pub = self.__conn.pubsub()
pub.subscribe(chan)
pub.parse_response()
return pub #订阅者
import s3 obj = s3.RedisHelper()
data = obj.subscribe('fm111.7')
print(data.parse_response()) #发布者
import s3 obj = s3.RedisHelper()
obj.public('alex db', 'fm111.7')

RabbitMQ

 #消费者
import pika connection = pika.BlockingConnection(pika.ConnectionParameters(host='127.0.0.1'))
channel = connection.channel()#创建对象 channel.queue_declare(queue = 'wocao')
def callback(ch,method,properties,body):
print("[x] Received %r"%body) channel.basic_consume(callback,queue = 'wocao',no_ack = True)
print('[*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming() #生产者
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(host='127.0.0.1'))
channel = connection.channel()
channel.queue_declare(queue = 'wocao')#指定一个队列,不存在此队列则创建
channel.basic_publish(exchange = '',routing_key = 'wocao',body = 'hello world!')
print("[x] Sent 'hello world!")
connection.close()

exchange type类型

#生产者
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(
host='192.168.11.87'))
channel = connection.channel()
#fanout类型,对绑定该exchange的队列实行广播
channel.exchange_declare(exchange='logs_fanout',
type='fanout') # 随机创建队列
result = channel.queue_declare(exclusive=True)
queue_name = result.method.queue
# 绑定exchange
channel.queue_bind(exchange='logs_fanout',
queue=queue_name) print(' [*] Waiting for logs. To exit press CTRL+C') def callback(ch, method, properties, body):
print(" [x] %r" % body) channel.basic_consume(callback,
queue=queue_name,
no_ack=True) channel.start_consuming()
#消费者
import pika #发送方
connection = pika.BlockingConnection(pika.ConnectionParameters(
host='192.168.11.87'))
channel = connection.channel() channel.exchange_declare(exchange='logs_fanout',
type='fanout') message = "what's the fuck"
#设置exchange的名
channel.basic_publish(exchange='logs_fanout',
routing_key='',
body=message)
print(" [x] Sent %r" % message)
connection.close()
 #根据关键字发送指定队列
#生产者(发布者)
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(
host = '127.0.0.1'))
channel = connection.channel() channel.exchange_declare(exchange='direct_logs_1',
type='direct') # 关键字发送到队列
#对error关键字队列发送指令
severity = 'error'
message = ''
channel.basic_publish(exchange = 'direct_logs_1',
routing_key = severity,
body = message)
print('[x] Sent %r:%r'%(severity,message))
connection.close()
#消费者(订阅者)
import pika
#消费者
connection = pika.BlockingConnection(pika.ConnectionParameters(
host = '127.0.0.1'))
channel = connection.channel()
channel.exchange_declare(exchange='direct_logs_1',
type = 'direct')#关键字发送到队列 result = channel.queue_declare(exclusive=True)
queue_name = result.method.queue
serverities = ['error','info','warning']
for severity in serverities:
channel.queue_bind(exchange='direct_logs_1',
queue = queue_name,
routing_key = severity)
def callback(ch,method,properties,body):
print('[x] %r:%r'%(method.routing_key,body)) channel.basic_consume(callback,
queue = queue_name,
no_ack = True)
channel.start_consuming()
 #实现消息不丢失接收方
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(host = '10.211.55.4'))
channel = connection.channel()
channel.queue_declare(queue = 'hello') def callback(ch,method,properties,body):
print('redeived %s'%body)
import time
time.sleep(10)
print('ok')
ch.basic_ack(delivery_tag= method.delivery_tag)
#no_ack = False接收方接受完请求后发送给对方一个接受成功的信号,如果没收到mq会重新将任务放到队列
channel.basic_consume(callback,queue = 'hello',no_ack=False)
print(' Waiting for messages.To exit press CTRL+C')
channel.start_consuming()
 #发送方
#实现消息不丢失
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(host = '10.211.55.4'))
channel = connection.channel()
channel.queue_declare(queue = 'hello',durable = True)
channel.basic_publish(exchange = '',routing_key = 'hello world',
properties = pika.BasicProperties(
delivery_mode=2,
))#发送方不丢失,发送方保持持久化
print(' Waiting for messages.To exit press CTRL+C')
channel.start_consuming()
 #接收方
import pika connection = pika.BlockingConnection(pika.ConnectionParameters(host='192.168.11.100'))
channel = connection.channel() channel.queue_declare(queue='hello', durable=True)
def callback(ch, method, properties, body):
print(" [x] Received %r" % body)
import time
time.sleep(10)
print 'ok'
ch.basic_ack(delivery_tag = method.delivery_tag)
channel.basic_consume(callback,
queue='hello',
no_ack=False)
channel.start_consuming()

RabbitMQ队列中默认情况下,接收方从队列中获取消息是顺序的,例如:接收方1只从队列中获取奇数的任务,接收方2只从队列中获取偶数任务

import pika

connection = pika.BlockingConnection(pika.ConnectionParameters(host='192.168.11.100'))
channel = connection.channel()
channel.queue_declare(queue='hello')
def callback(ch, method, properties, body):
print(" [x] Received %r" % body)
import time
time.sleep(10)
print 'ok'
ch.basic_ack(delivery_tag = method.delivery_tag)
#表示队列不分奇偶分配,谁来取任务就给谁
channel.basic_qos(prefetch_count=1)
channel.basic_consume(callback,
queue='hello',
no_ack=False)
print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()

RabbitMQ会重新将该任务添加到队列中

python之上下文管理、redis的发布订阅、rabbitmq的更多相关文章

  1. Python之上下文管理器

    # -*- coding: utf-8 -*- #python 27 #xiaodeng #Python之上下文管理器 #http://python.jobbole.com/82620/ #语法形式: ...

  2. Python之上下文管理

    http://www.cnblogs.com/coser/archive/2013/01/28/2880328.html 上下文管理协议为代码块提供包含初始化和清理操作的上下文环境.即便代码块发生异常 ...

  3. Redis之发布订阅

    一 什么是发布订阅 发布订阅模式又叫观察者模式,它定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖它的对象都将得到通知 Redis 发布订阅(pub/sub)是一种消息通信模式: ...

  4. [翻译] C# 8.0 新特性 Redis基本使用及百亿数据量中的使用技巧分享(附视频地址及观看指南) 【由浅至深】redis 实现发布订阅的几种方式 .NET Core开发者的福音之玩转Redis的又一傻瓜式神器推荐

    [翻译] C# 8.0 新特性 2018-11-13 17:04 by Rwing, 1179 阅读, 24 评论, 收藏, 编辑 原文: Building C# 8.0[译注:原文主标题如此,但内容 ...

  5. Redisson 分布式锁实现之前置篇 → Redis 的发布/订阅 与 Lua

    开心一刻 我找了个女朋友,挺丑的那一种,她也知道自己丑,平常都不好意思和我一块出门 昨晚,我带她逛超市,听到有两个人在我们背后小声嘀咕:"看咱前面,想不到这么丑都有人要." 女朋友 ...

  6. redis的发布订阅模式

    概要 redis的每个server实例都维护着一个保存服务器状态的redisServer结构 struct redisServer {     /* Pubsub */     // 字典,键为频道, ...

  7. StackExchange.Redis 使用-发布订阅 (二)

    使用Redis的发布订阅功能 redis另一个常见的用途是发布订阅功能 . 它非常的简单 ,当连接失败时 ConnectionMultiplexer 会自动重新进行订阅 . ISubscriber s ...

  8. .net core 使用Redis的发布订阅

    Redis是一个性能非常强劲的内存数据库,它一般是作为缓存来使用,但是他不仅仅可以用来作为缓存,比如著名的分布式框架dubbo就可以用Redis来做服务注册中心.接下来介绍一下.net core 使用 ...

  9. redis的发布订阅模式pubsub

    前言 redis支持发布订阅模式,在这个实现中,发送者(发送信息的客户端)不是将信息直接发送给特定的接收者(接收信息的客户端),而是将信息发送给频道(channel),然后由频道将信息转发给所有对这个 ...

随机推荐

  1. Spring boot 集成三种拦截方式

    三种拦截方式分别为: javax.servlet.Filter org.springframework.web.servlet.HandlerInterceptor org.aspectj.lang. ...

  2. TypeScript学习-TypeScript环境配置

    http://blog.csdn.net/shi_weihappy/article/details/49332091

  3. javaweb基础(36)_jdbc进行批处理

    在实际的项目开发中,有时候需要向数据库发送一批SQL语句执行,这时应避免向数据库一条条的发送执行,而应采用JDBC的批处理机制,以提升执行效率. JDBC实现批处理有两种方式:statement和pr ...

  4. 旋度定理(Curl Theorem)和散度定理(Divergence theorem)

    原文链接 首先说说格林公式(Green's theorem).对于一段封闭曲线,若其围城的区域D为单连通区域(内部任意曲线围城的区域都属于院区域),则有如下公式: 其中其中L为D的边界,取正方向.如果 ...

  5. Java 单词 day seven

    Constructor Constructor Constructor Constructor Constructor Constructor Constructor Constructor Cons ...

  6. 关于props的注意事项!

    起于昨晚大半夜在群里看到有人问这个问题,在子组件的data属性里重新赋值props属性 this.a = this.propA,不生效! 提示了他如果是异步的话,就要注意watch.决定今日敲个dem ...

  7. 【赛时总结】◇赛时·VI◇ Atcoder ABC-104

    ◇赛时·VI◇ ABC-104 ◆??? 莫名爆炸……ABC都AK不了 QwQ C题竟然沦落到卡数据的地步:D题没有思路,直接放弃 ⋋( ◕ ∧ ◕ )⋌ ◆ 题目&解析 ◇A题◇ Rated ...

  8. Ubuntu安装MySQL及使用Xshell连接MySQL出现的问题(2003-Can't connect to MySql server及1045错误)

    不管在什么地方,什么时候,学习是快速提升自己的能力的一种体现!!!!!!!!!!! 以下所有的命令都是在root用户下操作(如果还没有设置root密码)如下: 安装好Ubuntu系统之后,打开终端先设 ...

  9. Linux下vim操作的一些使用技巧

    以下均为个人在编程时对vim编辑器的一些心得,大神请指点,新手可以看过来 1.多文本编辑 vim -On/-on filename_1 … filename_n 如上所示,在要编辑的文件名前加上“-O ...

  10. python json.dumps raise TypeError(repr(o) + " is not JSON serializable") TypeError: 0 is not JSON serializable

    出错如题. 这个问题有可能是因为python的json.dumps没法识别dump内容里的某些数据类型导致的.我的问题是因为dict中含有numpy.int64,numpy.float等类型导致的,需 ...