#!/usr/bin/pythonimport Sys,time,json,loggingimport Queue, threading, Datetimefrom Lib.base.daemon import Daemonfrom Lib.queue.httpsqs.HttpsqsClient Import httpsqsclientfrom Lib.db.DbMongodb import Dbmongodblogging.basicconfig (level =logging. DEBUG, format= '% (asctime) s% (filename) s[line:% (lineno) d]% (levelname) s% (message) s ', datefmt = '%a,%d%b%Y%h:%m:%s ', filename= ' Myapp.log ', filemode= ' W ') queue = queue. Queue () Httpsqs = httpsqsclient (' 192.168.0.218 ', ' 1218 ', ' httpsqs.com ') db = Dbmongodb (' 192.168.0.119 ', ' TestDB ') Class Threadgethttpsqs (threading. Thread): def __init__ (self): threading. Thread.__init__ (self) Self.httpsqs = Httpsqs self.queue = Queue def run (self): while True: data = Self.httpsqs.get (' logtest ') if data is not None:self.queue.put (data) Logging.info (' Get:id%s, tablename%s '% (Self.getname (), DaTA)) Else:time.sleep (3) class Threadinsertdb (threading. Thread): def __init__ (self): threading. Thread.__init__ (self) self.queue = Queue Self.db = db def run (self): while True: Chunk = Self.queue.get () s = json.loads (chunk) tablename = s[' table '] data = s[' data '] Self.db.save (Tablename,data) logging.info (' Insert:id%s, tablename%s '% (Self.getname (), TableName )) Self.queue.task_done () class Mydaemon (Daemon): def _run (self): while True: For I in range (2): T = Threadgethttpsqs () #t. Setdaemon (True) T.start () For I in range (2): b = Threadinsertdb () #t. Setdaemon (True) B.start () #线程已经为永真循环, process can no longer cycle time.wait () if __name__ = = "__main__": Daemon = Mydaemon ('/tmp/daemon-example.pid ') If Len (sys.argv) = = 2:if ' s Tart ' = = Sys.argv[1]: Daemon.start () elif ' stop ' = = Sys.argv[1]: daemon.stop () elif ' r Estart ' = = Sys.argv[1]: Daemon.restart () else:print "Unknown Command" Sys.exit (2) Sys.exit (0) Else:print "Usage:%s start|stop|restart"% sys.argv[0] Sys.exit (2)