nats-server icon indicating copy to clipboard operation
nats-server copied to clipboard

server.Server.Start() doesn't block

Open trading-peter opened this issue 2 years ago • 1 comments

I tried the linked example code on how to embed a nats server into a go program. While doing so I noticed that the Start() function doesn't seem to block despite what the comments tell. Am I misunderstanding something or are the comments for the function wrong? Also, if it's correct that Start() internally starts a goroutine, how are we deferring actions to when the server was shutdown? Like clean up of other things for example.

package main

import (
	"fmt"
	"time"

	"github.com/nats-io/nats-server/v2/server"
	"github.com/nats-io/nats.go"
)

func main() {
	opts := &server.Options{}

	// Initialize new server with options
	ns, err := server.NewServer(opts)

	if err != nil {
		panic(err)
	}

	// Start the server via goroutine
        // go ns.Start()

        // NOTICE HOW IT'S NOT USING A GOROUTINE BUT THE CODE AFTER STILL RUNS
	ns.Start()

	// Wait for server to be ready for connections
	if !ns.ReadyForConnections(4 * time.Second) {
		panic("not ready for connection")
	}

	// Connect to server
	nc, err := nats.Connect(ns.ClientURL())

	if err != nil {
		panic(err)
	}

	subject := "my-subject"

	// Subscribe to the subject
	nc.Subscribe(subject, func(msg *nats.Msg) {
		// Print message data
		data := string(msg.Data)
		fmt.Println(data)

		// Shutdown the server (optional)
		ns.Shutdown()
	})

	// Publish data to the subject
	nc.Publish(subject, []byte("Hello embedded NATS!"))

	// Wait for server shutdown
	ns.WaitForShutdown()
}

trading-peter avatar Jul 13 '22 22:07 trading-peter

@trading-peter Oh my... yes, it seems that I made a change more than 2 years ago whereby Start() (that calls AcceptLoop) is no longer blocking since the actual accept loop is running in its own go routine.

So it is fine the way you are doing it (as you can see). That being said, in some conditions it could be that the server Start() takes time to run (with JetStream it could recover state and take time).

kozlovic avatar Jul 13 '22 22:07 kozlovic

Just ran into this ... One should update the comment on the Start() method :)

niondir avatar Jun 15 '23 13:06 niondir

Been updated for some time.

https://github.com/nats-io/nats-server/blob/main/server/server.go#L1678

derekcollison avatar Jun 15 '23 20:06 derekcollison