#!/usr/bin/python
import sys,time,json,logging
import queue, threading, datetime
from lib.base.daemon import daemon
from lib.queue.httpsqs.httpsqsclient import httpsqsclient
from lib.db.dbmongodb import dbmongodb
logging.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()
#线程已经为永真循环,进程不能再循环
time.wait()
if __name__ == “__main__”:
daemon = mydaemon(‘/tmp/daemon-example.pid’)
if len(sys.argv) == 2:
if ‘start’ == sys.argv[1]:
daemon.start()
elif ‘stop’ == sys.argv[1]:
daemon.stop()
elif ‘restart’ == 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)