SlideShare a Scribd company logo
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
Efficiency(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

More Related Content

What's hot

java 8 new features
java 8 new features java 8 new features
java 8 new features
Rohit Verma
 
An Introduction to Java Compiler and Runtime
An Introduction to Java Compiler and RuntimeAn Introduction to Java Compiler and Runtime
An Introduction to Java Compiler and Runtime
Omar Bashir
 
Apache Spark - Basics of RDD | Big Data Hadoop Spark Tutorial | CloudxLab
Apache Spark - Basics of RDD | Big Data Hadoop Spark Tutorial | CloudxLabApache Spark - Basics of RDD | Big Data Hadoop Spark Tutorial | CloudxLab
Apache Spark - Basics of RDD | Big Data Hadoop Spark Tutorial | CloudxLab
CloudxLab
 
为啥别读HotSpot VM的源码(2012-03-03)
为啥别读HotSpot VM的源码(2012-03-03)为啥别读HotSpot VM的源码(2012-03-03)
为啥别读HotSpot VM的源码(2012-03-03)
Kris Mok
 
Strings in Java
Strings in Java Strings in Java
Strings in Java
Hitesh-Java
 
Vectorized Query Execution in Apache Spark at Facebook
Vectorized Query Execution in Apache Spark at FacebookVectorized Query Execution in Apache Spark at Facebook
Vectorized Query Execution in Apache Spark at Facebook
Databricks
 
Data all over the place! How SQL and Apache Calcite bring sanity to streaming...
Data all over the place! How SQL and Apache Calcite bring sanity to streaming...Data all over the place! How SQL and Apache Calcite bring sanity to streaming...
Data all over the place! How SQL and Apache Calcite bring sanity to streaming...
Julian Hyde
 
Real Life Clean Architecture
Real Life Clean ArchitectureReal Life Clean Architecture
Real Life Clean Architecture
Mattia Battiston
 
Apache Helix DevOps & LSPE-IN Meetup
Apache Helix DevOps & LSPE-IN Meetup Apache Helix DevOps & LSPE-IN Meetup
Apache Helix DevOps & LSPE-IN Meetup
Shahnawaz Saifi
 
Writing and testing high frequency trading engines in java
Writing and testing high frequency trading engines in javaWriting and testing high frequency trading engines in java
Writing and testing high frequency trading engines in java
Peter Lawrey
 
Escalando apps com React e Type Script e SOLID
Escalando apps com React e Type Script e SOLIDEscalando apps com React e Type Script e SOLID
Escalando apps com React e Type Script e SOLID
Ruben Marcus Luz Paschoarelli
 
SpringBoot 3 Observability
SpringBoot 3 ObservabilitySpringBoot 3 Observability
SpringBoot 3 Observability
Knoldus Inc.
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
Jeevesh Pandey
 
The Eclipse Transformer Project
The Eclipse Transformer Project The Eclipse Transformer Project
The Eclipse Transformer Project
Jakarta_EE
 
Spring introduction
Spring introductionSpring introduction
Spring introduction
Manav Prasad
 
OpenJDK Concurrent Collectors
OpenJDK Concurrent CollectorsOpenJDK Concurrent Collectors
OpenJDK Concurrent Collectors
Monica Beckwith
 
Non blocking io with netty
Non blocking io with nettyNon blocking io with netty
Non blocking io with netty
Zauber
 
03 spark rdd operations
03 spark rdd operations03 spark rdd operations
03 spark rdd operations
Venkat Datla
 
Spring mvc
Spring mvcSpring mvc
Spring mvc
Pravin Pundge
 
Arrays in Java
Arrays in Java Arrays in Java
Arrays in Java
Hitesh-Java
 

What's hot (20)

java 8 new features
java 8 new features java 8 new features
java 8 new features
 
An Introduction to Java Compiler and Runtime
An Introduction to Java Compiler and RuntimeAn Introduction to Java Compiler and Runtime
An Introduction to Java Compiler and Runtime
 
Apache Spark - Basics of RDD | Big Data Hadoop Spark Tutorial | CloudxLab
Apache Spark - Basics of RDD | Big Data Hadoop Spark Tutorial | CloudxLabApache Spark - Basics of RDD | Big Data Hadoop Spark Tutorial | CloudxLab
Apache Spark - Basics of RDD | Big Data Hadoop Spark Tutorial | CloudxLab
 
为啥别读HotSpot VM的源码(2012-03-03)
为啥别读HotSpot VM的源码(2012-03-03)为啥别读HotSpot VM的源码(2012-03-03)
为啥别读HotSpot VM的源码(2012-03-03)
 
Strings in Java
Strings in Java Strings in Java
Strings in Java
 
Vectorized Query Execution in Apache Spark at Facebook
Vectorized Query Execution in Apache Spark at FacebookVectorized Query Execution in Apache Spark at Facebook
Vectorized Query Execution in Apache Spark at Facebook
 
Data all over the place! How SQL and Apache Calcite bring sanity to streaming...
Data all over the place! How SQL and Apache Calcite bring sanity to streaming...Data all over the place! How SQL and Apache Calcite bring sanity to streaming...
Data all over the place! How SQL and Apache Calcite bring sanity to streaming...
 
Real Life Clean Architecture
Real Life Clean ArchitectureReal Life Clean Architecture
Real Life Clean Architecture
 
Apache Helix DevOps & LSPE-IN Meetup
Apache Helix DevOps & LSPE-IN Meetup Apache Helix DevOps & LSPE-IN Meetup
Apache Helix DevOps & LSPE-IN Meetup
 
Writing and testing high frequency trading engines in java
Writing and testing high frequency trading engines in javaWriting and testing high frequency trading engines in java
Writing and testing high frequency trading engines in java
 
Escalando apps com React e Type Script e SOLID
Escalando apps com React e Type Script e SOLIDEscalando apps com React e Type Script e SOLID
Escalando apps com React e Type Script e SOLID
 
SpringBoot 3 Observability
SpringBoot 3 ObservabilitySpringBoot 3 Observability
SpringBoot 3 Observability
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
 
The Eclipse Transformer Project
The Eclipse Transformer Project The Eclipse Transformer Project
The Eclipse Transformer Project
 
Spring introduction
Spring introductionSpring introduction
Spring introduction
 
OpenJDK Concurrent Collectors
OpenJDK Concurrent CollectorsOpenJDK Concurrent Collectors
OpenJDK Concurrent Collectors
 
Non blocking io with netty
Non blocking io with nettyNon blocking io with netty
Non blocking io with netty
 
03 spark rdd operations
03 spark rdd operations03 spark rdd operations
03 spark rdd operations
 
Spring mvc
Spring mvcSpring mvc
Spring mvc
 
Arrays in Java
Arrays in Java Arrays in Java
Arrays in Java
 

Similar to 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 2013
Cosimo 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 Linardos
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 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-Malla
Spark 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 solutions
Kesav Kumar Kolla
 
Parsl: Pervasive Parallel Programming in Python
Parsl: Pervasive Parallel Programming in PythonParsl: Pervasive Parallel Programming in Python
Parsl: Pervasive Parallel Programming in Python
Daniel S. Katz
 
Docker serverless v1.0
Docker serverless v1.0Docker serverless v1.0
Docker serverless v1.0
Thomas Chacko
 
Hadoop MapReduce framework - Module 3
Hadoop MapReduce framework - Module 3Hadoop MapReduce framework - Module 3
Hadoop MapReduce framework - Module 3
Rohit Agrawal
 
Presentation of Python, Django, DockerStack
Presentation of Python, Django, DockerStackPresentation of Python, Django, DockerStack
Presentation of Python, Django, DockerStack
David Sanchez
 
Node.js Introduction
Node.js IntroductionNode.js Introduction
Node.js Introduction
Kelum Senanayake
 
Dragoncraft Architectural Overview
Dragoncraft Architectural OverviewDragoncraft Architectural Overview
Dragoncraft Architectural Overview
jessesanford
 
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 intosolrusingsparktrimmed
whoschek
 
Easy deployment & management of cloud apps
Easy deployment & management of cloud appsEasy deployment & management of cloud apps
Easy deployment & management of cloud appsDavid Cunningham
 

Similar to 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
 

Recently uploaded

How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
danishmna97
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
SOFTTECHHUB
 
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofszkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
Alex Pruden
 
Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
Zilliz
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
KAMESHS29
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
Pierluigi Pugliese
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
Quotidiano Piemontese
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
Neo4j
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
Neo4j
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
Octavian Nadolu
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
DianaGray10
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
sonjaschweigert1
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
SOFTTECHHUB
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Nexer Digital
 

Recently uploaded (20)

How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
 
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofszkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
 
Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
 

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 • 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
  • 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