This is a creation in
Article, where the information may have evolved or changed.
Not completed
Objective
NSQD is the main logical part of NSQ, please refer to the official documentation. We look directly at the code.
Entry function
The main function is located in
Github.com/nsqio/nsq/apps/nsqd/nsqd.go
func main() { prg := &program{} if err := svc.Run(prg, syscall.SIGINT, syscall.SIGTERM); err != nil { log.Fatal(err) }}
Wherein the SVC. Run is a service wrapper, from Go-svc. It passed in the service interface and did four things init, Start, notifysignal and Stop:
// Run runs your Service.//// Run will block until one of the signals specified in sig is received.// If sig is empty syscall.SIGINT and syscall.SIGTERM are used by default.func Run(service Service, sig ...os.Signal) error { env := environment{} if err := service.Init(env); err != nil { return err } if err := service.Start(); err != nil { return err } if len(sig) == 0 { sig = []os.Signal{syscall.SIGINT, syscall.SIGTERM} } signalChan := make(chan os.Signal, 1) signalNotify(signalChan, sig...) <-signalChan return service.Stop()}
Let's take a look at the program's implementation of the Service interface
Func (P *program) Init (Env Svc. Environment) Error {if Env. Iswindowsservice () {dir: = filepath. Dir (OS. ARGS[0]) return OS. Chdir (dir)} return Nil}func (P *program) Start () error {//ztd: Initialize option opts: = Nsqd. Newoptions ()//ZTD: Sets the accepted parameter flagset: = Nsqdflagset (opts) flagset.parse (OS. Args[1:] Rand. Seed (time. Now (). UTC (). Unixnano ())//ZTD: If only the version information is queried if Flagset.lookup ("version"). Value. (Flag. Getter). Get (). (BOOL) {FMT. Println (version. String ("NSQD")) OS. Exit (0)}//ZTD: If you specified the Conf file var cfg config configfile: = flagset.lookup ("config"). Value.string () if configfile! = "" {_, Err: = toml. DecodeFile (ConfigFile, &cfg) if err! = Nil {log. Fatalf ("error:failed to load Config file%s-%s", ConfigFile, err. Error ())}} cfg. Validate ()//ZTD: Merge the configuration options in the command line and configuration file. Resolve (opts, Flagset, cfg) nsqd: = Nsqd. The topic and channel information is stored in New (opts)//ztd:metadata err: = Nsqd. LoadmEtadata () if err! = Nil {log. Fatalf ("ERROR:%s", err.) Error ())}//ZTD: It is not clear why you read it immediately and write err = Nsqd. Persistmetadata () if err! = Nil {log. Fatalf ("error:failed to persist metadata-%s", Err. Error ())} nsqd. Main () P.nsqd = Nsqd return Nil}func (P *program) Stop () error {if P.NSQD! = nil {p.nsqd.exit ()} Return nil}
NSQD. Main ()