Rocket is a lightweight, multi-threaded web framework that conforms to the WSGI specification.
The rocket uses a thread to listen to the connection, receives the connection and puts it into the queue, which is processed by the worker thread.
Rocket contains the following properties:
- Method-a string value indicating the type of Worker to use to answer the requests received by Rocket. The default is Wsgi and would invoke the Wsgiworker class for handling requests. Go to themethods sections to see all available methods.
- App_info-a dictionary that holds information that the Worker class specified in method would use for Configurati On. See the documentation in the Methods sections for the Worker class you is using for details on what to put in this diction ary.
- Min_threads-an integer number of minimum Worker threads to run. This number must is greater than 0. Rocket always has at least min_threads number of threads running at a time unless it's in the process of S Hutting down.
- Max_threads-an integer number of maximum Worker threads. This number must is greater than min_threads or 0. A max_threads of 0 (zero) indicates there to be no maximum thread count. Rocket would continue generating threads so long as there is unanswered connections in the request queue. If The running environment is limited by what many threads a process can own, consider that on addition to max_threads ther E would also be a monitor thread and listening thread running.
- Queue_size-an integer number of connections allowed to be queued before Rocket accepts them. This are passed to the listen () function in the operating system ' s socket library. It defaults toNone which either uses the operating system ' s maximum or 5 if the OS Max was not discoverable.
- Timeout-an integer number of seconds to listen to a connection for a new request before closing it. Defaults to .
- Handle_signals-a Boolean indicating whether or not Rocket should respond to Unix-style process signals (if the platform Supports signals). Defaults to True.
Min_threads must be a number greater than 0, rocket at the same time must have greater than min_threads in execution, the default value is 10
Max_threads is the maximum number of threads executing at the same time, the default is unlimited, for CPython because of the Gil, so there is a lot of threads there is no problem; for Jpython, because it is true multi-threading, if the bottleneck of the Web is CPU, it is recommended Max_ Threads is 1.5 times times the number of CPU cores, avoiding multi-threaded switching to reduce efficiency.
Queue_size refers to the number of connections that can be received by default, which is usually determined by the system.
The rocket framework is used in web.py and the initial code is as follows:
classRocket (object):"""The Rocket class is responsible for handling threads and accepting and dispatching connections.""" def __init__(self, interfaces=('127.0.0.1', 8000), Method='Wsgi', App_info=None, Min_threads=None, Max_threads=None, Queue_size=None, timeout=600, Handle_signals=True): Self.handle_signals=handle_signals Self.startstop_lock=Lock () self.timeout=Timeoutif notisinstance (interfaces, list): Self.interfaces=[Interfaces]Else: Self.interfaces=InterfacesifMin_threads isnone:min_threads= defaults['min_threads'] ifMax_threads isnone:max_threads= defaults['max_threads'] if notqueue_size:ifHASATTR (Socket,'Somaxconn'): Queue_size=socket. SomaxconnElse: Queue_size= defaults['listen_queue_size'] ifMax_threads andQueue_size >max_threads:queue_size=max_threadsifisinstance (App_info, dict): app_info['Server_software'] =Server_software Self.monitor_queue=Queue () self.active_queue=Queue () Self._threadpool=ThreadPool (Get_method (method), App_info=App_info, Active_queue=Self.active_queue, Monitor_queue=Self.monitor_queue, Min_threads=min_threads, Max_threads=max_threads)#Build Our socket listenersSelf.listeners =[Listener (i, Queue_size, Self.active_queue) forIinchSelf.interfaces] forNdxinchRange (len (self.listeners)-1, 0, 1): if notSelf.listeners[ndx].ready:delSelf.listeners[ndx]if notself.listeners:log.critical ("No interfaces to listen on...closing.") Sys.exit (1) def_sigterm (self, Signum, frame): Log.info ('Received SIGTERM') self.stop ()def_sighup (self, Signum, frame): Log.info ('Received SIGHUP') Self.restart ()defStart (self, background=False): Log.info ('Starting%s'%server_software) Self.startstop_lock.acquire ()Try: #Set up our shutdown signals ifself.handle_signals:Try: Importsignal signal.signal (signal. SIGTERM, Self._sigterm) signal.signal (signal. SIGUSR1, Self._sighup)except: Log.debug ('This platform does is not a support signals.') #Start Our worker threadsSelf._threadpool.start ()#Start our monitor threadSelf._monitor =Monitor (Self.monitor_queue, Self.active_queue, Self.timeout, Self._threadpool) Self._monitor.setdaemon (True) sel F._monitor.start ()#I know that EXPR and A or B are bad but I'm keeping it for Py2.4 #compatibility.Str_extract =LambdaL: (l.addr, L.port, l.secure and '*' or "') msg='Listening on sockets:'msg+=', '. Join (['%s:%i%s'% Str_extract (l) forLinchSelf.listeners]) log.info (msg) forLinchSelf.listeners:l.start ()finally: Self.startstop_lock.release ()ifbackground:return whileself._monitor.isalive ():Try: Time.sleep (thread_stop_check_interval)exceptKeyboardinterrupt:#Capture a keyboard interrupt when running from a console Break except: ifself._monitor.isalive (): Log.error (Traceback.format_exc ())Continue returnself.stop ()defStop (self, stoplogging=False): Log.info ('Stopping%s'%server_software) Self.startstop_lock.acquire ()Try: #Stop Listeners forLinchSelf.listeners:l.ready=False#encourage a context switchTime.sleep (0.01) forLinchself.listeners:ifl.isalive (): L.join ()#Stop Monitorself._monitor.stop ()ifself._monitor.isalive (): Self._monitor.join ()#Stop Worker Threadsself._threadpool.stop ()ifStoplogging:logging.shutdown () msg="calling Logging.shutdown () is now the responsibility of the application developer. Please update your applications to no longer call Rocket.stop (True)" Try: ImportWarningsRaisewarnings. Deprecationwarning (msg)exceptImporterror:Raiseruntimeerror (msg)finally: Self.startstop_lock.release ()defRestart (self): Self.stop () Self.start ()
The Start method performs the following steps:
1. Start and close lock and lock
2. Registration Termination and restart signal
3. Start worker thread pool
4. Start the monitoring thread, add the monitoring thread to the thread pool
5. Start all Listening threads
6. Release the start-off lock
7, enter while (monitor thread survival) cycle, 1s per sleep
Stop method:
1. Start and close lock and lock
2. All listener threads set ready to be marked as false
3. Wait for all listener threads to end
4. Wait for the monitoring thread to end
5. Close worker thread pool
6. Output Close Log
7. Release the start-off lock
web.py Learning (-) Rocket web framework