[关闭]
@zengxiankui 2017-08-04T13:18:33.000000Z 字数 1148 阅读 1395

Python-Redis发布订阅

Python


发布者DEMO代码

  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. #File: publish.py 信息发布者;
  4. import sys, redis;
  5. reload(sys);
  6. sys.setdefaultencoding('utf8');
  7. ###连接池方式OK
  8. pool = redis.ConnectionPool(host = "10.0.30.91", port = 6379, password = "hsb_redis_123", db = 0);
  9. r = redis.StrictRedis(connection_pool = pool);
  10. ###连接池方式OK
  11. #r = redis.StrictRedis(host = "10.0.30.91", port = 6379, password = "hsb_redis_123", db = 0);
  12. while(True):
  13. input = raw_input("publish>>> ");
  14. r.publish("ch2", input);
  15. if("exit" == input):
  16. print("停止发布");
  17. break;
  18. else:pass;
  19. else:pass;
  20. print("EXIT");

订阅者DEMO代码

  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. #File: subscribe.py 信息订阅者;
  4. import sys, redis;
  5. reload(sys);
  6. sys.setdefaultencoding('utf8');
  7. ###连接池方式OK
  8. pool = redis.ConnectionPool(host = "10.0.30.91", port = 6379, password = "hsb_redis_123", db = 0);
  9. r = redis.StrictRedis(connection_pool = pool);
  10. ###单链接方式OK
  11. #r = redis.StrictRedis(host = "10.0.30.91", port = 6379, password = "hsb_redis_123", db = 0);
  12. p = r.pubsub();
  13. p.subscribe("ch2");
  14. for item in p.listen():
  15. print(item);
  16. if(item["type"] == "subscribe"):
  17. print("Subscribe OK!");
  18. continue;
  19. else:pass;
  20. if(item["type"] == "message"):
  21. data = item["data"];
  22. print(data);
  23. if("exit" == data):
  24. break;
  25. else:pass;
  26. else:pass;
  27. else:pass;
  28. p.unsubscribe("ch2");
  29. print("EXIT");
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注