SlideShare ist ein Scribd-Unternehmen logo
1 von 15
Downloaden Sie, um offline zu lesen
NSQ & Python Worker
Felinx Lee
May 18, 2013
NSQ is a realtime message processing
system designed to operate at bitly's scale,
handling billions of messages per day.
Keywords
• realtime
• distributed
• decentralized
• fault tolerance
• message delivery guarantee
• developed in Go Language
• developed by bitly
Features
• no SPOF, designed for distributed environments
• messages are guaranteed to be delivered at least once
• low-latency push based message delivery (performance)
• combination load-balanced and multicast style message routing
• configurable high-water mark after which messages are transparently kept on
disk
• few dependencies, easy to deploy, and sane, bounded, default configuration
• runtime discovery service for consumers to find producers (nsqlookupd)
• HTTP interface for stats, administrative actions, and producers (no client
libraries needed!)
• memcached-like TCP protocol for producers/consumers
Topics&Channels
Efciency(Push)
Bounded Memory
Footprint
In Production
Bootstrap
def main():
worker = load_worker()
logging.debug("Starting worker: %s" % worker)
r = nsq.Reader(worker.tasks,
lookupd_http_addresses=options.nsqlookupd_http_addresses,
topic=options.topic, channel=options.channel)
# override default preprocess and validate method with worker's method
r.validate_message = worker.validate_message
r.preprocess_message = worker.preprocess_message
nsq.run()
if __name__ == "__main__":
main()
def load_worker(workers_dir=None):
"""Load worker according to topic and channel options.
Preload all of workers to make tornado options work like a magic,
so a worker can define custom options in worker's header.
It only loads worker from file named as {topic}/{topic}_{channel}_worker.py,
eg. apiview/apiview_pageview_worker.py, the other files will be ignored.
"""
# Preload all of workers
if workers_dir is None:
workers_dir = os.path.dirname(os.path.abspath(__file__))
for d in os.listdir(workers_dir):
dir_ = os.path.join(workers_dir, d)
if os.path.isdir(dir_):
# ...
# Enable tornado command line options
options.parse_command_line()
# Then load the worker object according to topic and channel options.
try:
worker, name = _load_worker(options.topic, options.channel)
if worker:
return worker()
else:
raise ImportError("%s not found!" % name)
except ImportError, e:
logging.error(traceback.format_exc())
raise e
Loader
class Worker(object):
def preprocess_message(self, message):
pass
def validate_message(self, message):
pass
@property
def tasks(self):
_tasks = {}
for func in dir(self):
if func.endswith("_task"):
_tasks[func] = _task(getattr(self, func))
return _tasks
def _task(func):
"""Worker task decorator"""
q = _nsq_processed_messages_queues.get(func.__name__, None)
if q is None:
q = deque(maxlen=options.nsq_max_processed_messages_queue)
_nsq_processed_messages_queues[func.__name__] = q
def wrapper(message):
logging.debug("Raw message: %s, %s", message.id, message.body)
if message.id not in q:
try:
r = func(message)
if r:
q.append(message.id)
return r
except Exception, e:
logging.error(e)
logging.error(traceback.format_exc())
return True
return wrapper
Worker
Demo
import logging
from tornado.options import options, define
from nsqworker.workers.worker import Worker
define("demoname", "demo")
class TopicChannelWorker(Worker):
def demo_task(self, message):
logging.info("%s: %s/%s, message: %s", options.demoname,
options.topic, options.channel, message.body)
return True
Publish
class MainHandler(tornado.web.RequestHandler):
@property
def nsq(self):
return self.application.nsq
def get(self):
topic = "log"
msg = "Hello world"
msg_cn = "Hello 世界"
self.nsq.pub(topic, msg) # pub
self.nsq.mpub(topic, [msg, msg_cn]) # mpub
# customize callback
callback = functools.partial(self.finish_pub, topic=topic, msg=msg)
self.nsq.pub(topic, msg, callback=callback)
self.write(msg)
def finish_pub(self, conn, data, topic, msg):
if isinstance(data, Error):
# try to re-pub message again if pub failed
self.nsq.pub(topic, msg)
Reference
• https://github.com/bitly/nsq
• https://github.com/bitly/pynsq
• https://speakerdeck.com/snakes/nsq-nyc-golang-meetup
• https://github.com/bitly/nsq/blob/master/docs/protocol.md
• https://github.com/bitly/nsq/blob/master/docs/building_client_libraries.md
• https://github.com/felinx/nsqworker

Weitere ähnliche Inhalte

Was ist angesagt?

DoS and DDoS mitigations with eBPF, XDP and DPDK
DoS and DDoS mitigations with eBPF, XDP and DPDKDoS and DDoS mitigations with eBPF, XDP and DPDK
DoS and DDoS mitigations with eBPF, XDP and DPDKMarian Marinov
 
SRv6 study
SRv6 studySRv6 study
SRv6 studyHiro Mura
 
ATSC 3.0, MMT, Multicast
ATSC 3.0, MMT, MulticastATSC 3.0, MMT, Multicast
ATSC 3.0, MMT, MulticastMasaaki Nabeshima
 
Apache Hadoopの未来 3系になって何が変わるのか?
Apache Hadoopの未来 3系になって何が変わるのか?Apache Hadoopの未来 3系になって何が変わるのか?
Apache Hadoopの未来 3系になって何が変わるのか?NTT DATA OSS Professional Services
 
Kernel Recipes 2019 - Faster IO through io_uring
Kernel Recipes 2019 - Faster IO through io_uringKernel Recipes 2019 - Faster IO through io_uring
Kernel Recipes 2019 - Faster IO through io_uringAnne Nicolas
 
DPDK (Data Plane Development Kit)
DPDK (Data Plane Development Kit) DPDK (Data Plane Development Kit)
DPDK (Data Plane Development Kit) ymtech
 
Lagopus + DockerのDPDK接続
Lagopus + DockerのDPDK接続Lagopus + DockerのDPDK接続
Lagopus + DockerのDPDK接続Tomoya Hibi
 
Linux Networking Explained
Linux Networking ExplainedLinux Networking Explained
Linux Networking ExplainedThomas Graf
 
Service Function Chaining with SRv6
Service Function Chaining with SRv6Service Function Chaining with SRv6
Service Function Chaining with SRv6Ahmed AbdelSalam
 
Linux Network Stack
Linux Network StackLinux Network Stack
Linux Network StackAdrien Mahieux
 
Improving Kafka at-least-once performance at Uber
Improving Kafka at-least-once performance at UberImproving Kafka at-least-once performance at Uber
Improving Kafka at-least-once performance at UberYing Zheng
 
DPDKによる高速コンテナネットワーキング
DPDKによる高速コンテナネットワーキングDPDKによる高速コンテナネットワーキング
DPDKによる高速コンテナネットワーキングTomoya Hibi
 
Kafka to the Maxka - (Kafka Performance Tuning)
Kafka to the Maxka - (Kafka Performance Tuning)Kafka to the Maxka - (Kafka Performance Tuning)
Kafka to the Maxka - (Kafka Performance Tuning)DataWorks Summit
 
VXLAN and FRRouting
VXLAN and FRRoutingVXLAN and FRRouting
VXLAN and FRRoutingFaisal Reza
 
SHARP: In-Network Scalable Hierarchical Aggregation and Reduction Protocol
SHARP: In-Network Scalable Hierarchical Aggregation and Reduction ProtocolSHARP: In-Network Scalable Hierarchical Aggregation and Reduction Protocol
SHARP: In-Network Scalable Hierarchical Aggregation and Reduction Protocolinside-BigData.com
 
3GPP LTE Detailed explanation 1 (Random Access)
3GPP LTE Detailed explanation 1 (Random Access)3GPP LTE Detailed explanation 1 (Random Access)
3GPP LTE Detailed explanation 1 (Random Access)Ryuichi Yasunaga
 
DPDK KNI interface
DPDK KNI interfaceDPDK KNI interface
DPDK KNI interfaceDenys Haryachyy
 
NATS vs HTTP for Interservice Communication
NATS vs HTTP for Interservice CommunicationNATS vs HTTP for Interservice Communication
NATS vs HTTP for Interservice CommunicationNATS
 

Was ist angesagt? (20)

DoS and DDoS mitigations with eBPF, XDP and DPDK
DoS and DDoS mitigations with eBPF, XDP and DPDKDoS and DDoS mitigations with eBPF, XDP and DPDK
DoS and DDoS mitigations with eBPF, XDP and DPDK
 
SRv6 study
SRv6 studySRv6 study
SRv6 study
 
ATSC 3.0, MMT, Multicast
ATSC 3.0, MMT, MulticastATSC 3.0, MMT, Multicast
ATSC 3.0, MMT, Multicast
 
Apache Hadoopの未来 3系になって何が変わるのか?
Apache Hadoopの未来 3系になって何が変わるのか?Apache Hadoopの未来 3系になって何が変わるのか?
Apache Hadoopの未来 3系になって何が変わるのか?
 
Kernel Recipes 2019 - Faster IO through io_uring
Kernel Recipes 2019 - Faster IO through io_uringKernel Recipes 2019 - Faster IO through io_uring
Kernel Recipes 2019 - Faster IO through io_uring
 
DPDK (Data Plane Development Kit)
DPDK (Data Plane Development Kit) DPDK (Data Plane Development Kit)
DPDK (Data Plane Development Kit)
 
Lagopus + DockerのDPDK接続
Lagopus + DockerのDPDK接続Lagopus + DockerのDPDK接続
Lagopus + DockerのDPDK接続
 
Linux Networking Explained
Linux Networking ExplainedLinux Networking Explained
Linux Networking Explained
 
Service Function Chaining with SRv6
Service Function Chaining with SRv6Service Function Chaining with SRv6
Service Function Chaining with SRv6
 
Linux Network Stack
Linux Network StackLinux Network Stack
Linux Network Stack
 
Improving Kafka at-least-once performance at Uber
Improving Kafka at-least-once performance at UberImproving Kafka at-least-once performance at Uber
Improving Kafka at-least-once performance at Uber
 
DPDKによる高速コンテナネットワーキング
DPDKによる高速コンテナネットワーキングDPDKによる高速コンテナネットワーキング
DPDKによる高速コンテナネットワーキング
 
Kafka to the Maxka - (Kafka Performance Tuning)
Kafka to the Maxka - (Kafka Performance Tuning)Kafka to the Maxka - (Kafka Performance Tuning)
Kafka to the Maxka - (Kafka Performance Tuning)
 
VXLAN and FRRouting
VXLAN and FRRoutingVXLAN and FRRouting
VXLAN and FRRouting
 
Raft
RaftRaft
Raft
 
SHARP: In-Network Scalable Hierarchical Aggregation and Reduction Protocol
SHARP: In-Network Scalable Hierarchical Aggregation and Reduction ProtocolSHARP: In-Network Scalable Hierarchical Aggregation and Reduction Protocol
SHARP: In-Network Scalable Hierarchical Aggregation and Reduction Protocol
 
3GPP LTE Detailed explanation 1 (Random Access)
3GPP LTE Detailed explanation 1 (Random Access)3GPP LTE Detailed explanation 1 (Random Access)
3GPP LTE Detailed explanation 1 (Random Access)
 
DPDK KNI interface
DPDK KNI interfaceDPDK KNI interface
DPDK KNI interface
 
NATS vs HTTP for Interservice Communication
NATS vs HTTP for Interservice CommunicationNATS vs HTTP for Interservice Communication
NATS vs HTTP for Interservice Communication
 
NAT64 Overview
NAT64 OverviewNAT64 Overview
NAT64 Overview
 

Ähnlich wie Nsq & python worker

Introducing Node.js in an Oracle technology environment (including hands-on)
Introducing Node.js in an Oracle technology environment (including hands-on)Introducing Node.js in an Oracle technology environment (including hands-on)
Introducing Node.js in an Oracle technology environment (including hands-on)Lucas Jellema
 
Declarative Infrastructure Tools
Declarative Infrastructure Tools Declarative Infrastructure Tools
Declarative Infrastructure Tools Yulia Shcherbachova
 
Puppet at Opera Sofware - PuppetCamp Oslo 2013
Puppet at Opera Sofware - PuppetCamp Oslo 2013Puppet at Opera Sofware - PuppetCamp Oslo 2013
Puppet at Opera Sofware - PuppetCamp Oslo 2013Cosimo Streppone
 
Hack Like It's 2013 (The Workshop)
Hack Like It's 2013 (The Workshop)Hack Like It's 2013 (The Workshop)
Hack Like It's 2013 (The Workshop)Itzik Kotler
 
TorqueBox: The beauty of Ruby with the power of JBoss. Presented at Devnexus...
TorqueBox: The beauty of Ruby with the power of JBoss.  Presented at Devnexus...TorqueBox: The beauty of Ruby with the power of JBoss.  Presented at Devnexus...
TorqueBox: The beauty of Ruby with the power of JBoss. Presented at Devnexus...bobmcwhirter
 
Apache Spark Workshop, Apr. 2016, Euangelos Linardos
Apache Spark Workshop, Apr. 2016, Euangelos LinardosApache Spark Workshop, Apr. 2016, Euangelos Linardos
Apache Spark Workshop, Apr. 2016, Euangelos LinardosEuangelos Linardos
 
An Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAn Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAdam Getchell
 
Kerberizing Spark: Spark Summit East talk by Abel Rincon and Jorge Lopez-Malla
Kerberizing Spark: Spark Summit East talk by Abel Rincon and Jorge Lopez-MallaKerberizing Spark: Spark Summit East talk by Abel Rincon and Jorge Lopez-Malla
Kerberizing Spark: Spark Summit East talk by Abel Rincon and Jorge Lopez-MallaSpark Summit
 
Introduction to Node (15th May 2017)
Introduction to Node (15th May 2017)Introduction to Node (15th May 2017)
Introduction to Node (15th May 2017)Lucas Jellema
 
Docker practical solutions
Docker practical solutionsDocker practical solutions
Docker practical solutionsKesav Kumar Kolla
 
Parsl: Pervasive Parallel Programming in Python
Parsl: Pervasive Parallel Programming in PythonParsl: Pervasive Parallel Programming in Python
Parsl: Pervasive Parallel Programming in PythonDaniel S. Katz
 
Docker serverless v1.0
Docker serverless v1.0Docker serverless v1.0
Docker serverless v1.0Thomas Chacko
 
Hadoop MapReduce framework - Module 3
Hadoop MapReduce framework - Module 3Hadoop MapReduce framework - Module 3
Hadoop MapReduce framework - Module 3Rohit Agrawal
 
Presentation of Python, Django, DockerStack
Presentation of Python, Django, DockerStackPresentation of Python, Django, DockerStack
Presentation of Python, Django, DockerStackDavid Sanchez
 
Node.js Introduction
Node.js IntroductionNode.js Introduction
Node.js IntroductionKelum Senanayake
 
Dragoncraft Architectural Overview
Dragoncraft Architectural OverviewDragoncraft Architectural Overview
Dragoncraft Architectural Overviewjessesanford
 
Leonid Vasilyev "Building, deploying and running production code at Dropbox"
Leonid Vasilyev  "Building, deploying and running production code at Dropbox"Leonid Vasilyev  "Building, deploying and running production code at Dropbox"
Leonid Vasilyev "Building, deploying and running production code at Dropbox"IT Event
 
PuppetDB: Sneaking Clojure into Operations
PuppetDB: Sneaking Clojure into OperationsPuppetDB: Sneaking Clojure into Operations
PuppetDB: Sneaking Clojure into Operationsgrim_radical
 
Ingesting hdfs intosolrusingsparktrimmed
Ingesting hdfs intosolrusingsparktrimmedIngesting hdfs intosolrusingsparktrimmed
Ingesting hdfs intosolrusingsparktrimmedwhoschek
 
Easy deployment & management of cloud apps
Easy deployment & management of cloud appsEasy deployment & management of cloud apps
Easy deployment & management of cloud appsDavid Cunningham
 

Ähnlich wie Nsq & python worker (20)

Introducing Node.js in an Oracle technology environment (including hands-on)
Introducing Node.js in an Oracle technology environment (including hands-on)Introducing Node.js in an Oracle technology environment (including hands-on)
Introducing Node.js in an Oracle technology environment (including hands-on)
 
Declarative Infrastructure Tools
Declarative Infrastructure Tools Declarative Infrastructure Tools
Declarative Infrastructure Tools
 
Puppet at Opera Sofware - PuppetCamp Oslo 2013
Puppet at Opera Sofware - PuppetCamp Oslo 2013Puppet at Opera Sofware - PuppetCamp Oslo 2013
Puppet at Opera Sofware - PuppetCamp Oslo 2013
 
Hack Like It's 2013 (The Workshop)
Hack Like It's 2013 (The Workshop)Hack Like It's 2013 (The Workshop)
Hack Like It's 2013 (The Workshop)
 
TorqueBox: The beauty of Ruby with the power of JBoss. Presented at Devnexus...
TorqueBox: The beauty of Ruby with the power of JBoss.  Presented at Devnexus...TorqueBox: The beauty of Ruby with the power of JBoss.  Presented at Devnexus...
TorqueBox: The beauty of Ruby with the power of JBoss. Presented at Devnexus...
 
Apache Spark Workshop, Apr. 2016, Euangelos Linardos
Apache Spark Workshop, Apr. 2016, Euangelos LinardosApache Spark Workshop, Apr. 2016, Euangelos Linardos
Apache Spark Workshop, Apr. 2016, Euangelos Linardos
 
An Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAn Overview Of Python With Functional Programming
An Overview Of Python With Functional Programming
 
Kerberizing Spark: Spark Summit East talk by Abel Rincon and Jorge Lopez-Malla
Kerberizing Spark: Spark Summit East talk by Abel Rincon and Jorge Lopez-MallaKerberizing Spark: Spark Summit East talk by Abel Rincon and Jorge Lopez-Malla
Kerberizing Spark: Spark Summit East talk by Abel Rincon and Jorge Lopez-Malla
 
Introduction to Node (15th May 2017)
Introduction to Node (15th May 2017)Introduction to Node (15th May 2017)
Introduction to Node (15th May 2017)
 
Docker practical solutions
Docker practical solutionsDocker practical solutions
Docker practical solutions
 
Parsl: Pervasive Parallel Programming in Python
Parsl: Pervasive Parallel Programming in PythonParsl: Pervasive Parallel Programming in Python
Parsl: Pervasive Parallel Programming in Python
 
Docker serverless v1.0
Docker serverless v1.0Docker serverless v1.0
Docker serverless v1.0
 
Hadoop MapReduce framework - Module 3
Hadoop MapReduce framework - Module 3Hadoop MapReduce framework - Module 3
Hadoop MapReduce framework - Module 3
 
Presentation of Python, Django, DockerStack
Presentation of Python, Django, DockerStackPresentation of Python, Django, DockerStack
Presentation of Python, Django, DockerStack
 
Node.js Introduction
Node.js IntroductionNode.js Introduction
Node.js Introduction
 
Dragoncraft Architectural Overview
Dragoncraft Architectural OverviewDragoncraft Architectural Overview
Dragoncraft Architectural Overview
 
Leonid Vasilyev "Building, deploying and running production code at Dropbox"
Leonid Vasilyev  "Building, deploying and running production code at Dropbox"Leonid Vasilyev  "Building, deploying and running production code at Dropbox"
Leonid Vasilyev "Building, deploying and running production code at Dropbox"
 
PuppetDB: Sneaking Clojure into Operations
PuppetDB: Sneaking Clojure into OperationsPuppetDB: Sneaking Clojure into Operations
PuppetDB: Sneaking Clojure into Operations
 
Ingesting hdfs intosolrusingsparktrimmed
Ingesting hdfs intosolrusingsparktrimmedIngesting hdfs intosolrusingsparktrimmed
Ingesting hdfs intosolrusingsparktrimmed
 
Easy deployment & management of cloud apps
Easy deployment & management of cloud appsEasy deployment & management of cloud apps
Easy deployment & management of cloud apps
 

KĂźrzlich hochgeladen

How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo GarcĂ­a Lavilla
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 

KĂźrzlich hochgeladen (20)

How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 

Nsq & python worker

  • 1. NSQ & Python Worker Felinx Lee May 18, 2013
  • 2. NSQ is a realtime message processing system designed to operate at bitly's scale, handling billions of messages per day.
  • 3. Keywords • realtime • distributed • decentralized • fault tolerance • message delivery guarantee • developed in Go Language • developed by bitly
  • 4. Features • no SPOF, designed for distributed environments • messages are guaranteed to be delivered at least once • low-latency push based message delivery (performance) • combination load-balanced and multicast style message routing • congurable high-water mark after which messages are transparently kept on disk • few dependencies, easy to deploy, and sane, bounded, default conguration • runtime discovery service for consumers to nd producers (nsqlookupd) • HTTP interface for stats, administrative actions, and producers (no client libraries needed!) • memcached-like TCP protocol for producers/consumers
  • 5.
  • 10. Bootstrap def main(): worker = load_worker() logging.debug("Starting worker: %s" % worker) r = nsq.Reader(worker.tasks, lookupd_http_addresses=options.nsqlookupd_http_addresses, topic=options.topic, channel=options.channel) # override default preprocess and validate method with worker's method r.validate_message = worker.validate_message r.preprocess_message = worker.preprocess_message nsq.run() if __name__ == "__main__": main()
  • 11. def load_worker(workers_dir=None): """Load worker according to topic and channel options. Preload all of workers to make tornado options work like a magic, so a worker can define custom options in worker's header. It only loads worker from file named as {topic}/{topic}_{channel}_worker.py, eg. apiview/apiview_pageview_worker.py, the other files will be ignored. """ # Preload all of workers if workers_dir is None: workers_dir = os.path.dirname(os.path.abspath(__file__)) for d in os.listdir(workers_dir): dir_ = os.path.join(workers_dir, d) if os.path.isdir(dir_): # ... # Enable tornado command line options options.parse_command_line() # Then load the worker object according to topic and channel options. try: worker, name = _load_worker(options.topic, options.channel) if worker: return worker() else: raise ImportError("%s not found!" % name) except ImportError, e: logging.error(traceback.format_exc()) raise e Loader
  • 12. class Worker(object): def preprocess_message(self, message): pass def validate_message(self, message): pass @property def tasks(self): _tasks = {} for func in dir(self): if func.endswith("_task"): _tasks[func] = _task(getattr(self, func)) return _tasks def _task(func): """Worker task decorator""" q = _nsq_processed_messages_queues.get(func.__name__, None) if q is None: q = deque(maxlen=options.nsq_max_processed_messages_queue) _nsq_processed_messages_queues[func.__name__] = q def wrapper(message): logging.debug("Raw message: %s, %s", message.id, message.body) if message.id not in q: try: r = func(message) if r: q.append(message.id) return r except Exception, e: logging.error(e) logging.error(traceback.format_exc()) return True return wrapper Worker
  • 13. Demo import logging from tornado.options import options, define from nsqworker.workers.worker import Worker define("demoname", "demo") class TopicChannelWorker(Worker): def demo_task(self, message): logging.info("%s: %s/%s, message: %s", options.demoname, options.topic, options.channel, message.body) return True
  • 14. Publish class MainHandler(tornado.web.RequestHandler): @property def nsq(self): return self.application.nsq def get(self): topic = "log" msg = "Hello world" msg_cn = "Hello 世界" self.nsq.pub(topic, msg) # pub self.nsq.mpub(topic, [msg, msg_cn]) # mpub # customize callback callback = functools.partial(self.finish_pub, topic=topic, msg=msg) self.nsq.pub(topic, msg, callback=callback) self.write(msg) def finish_pub(self, conn, data, topic, msg): if isinstance(data, Error): # try to re-pub message again if pub failed self.nsq.pub(topic, msg)
  • 15. Reference • https://github.com/bitly/nsq • https://github.com/bitly/pynsq • https://speakerdeck.com/snakes/nsq-nyc-golang-meetup • https://github.com/bitly/nsq/blob/master/docs/protocol.md • https://github.com/bitly/nsq/blob/master/docs/building_client_libraries.md • https://github.com/felinx/nsqworker