NatsServer_test.go 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package test
  2. import (
  3. "fmt"
  4. "github.com/nats-io/nats-server/v2/server"
  5. "github.com/nats-io/nats.go"
  6. "testing"
  7. "time"
  8. )
  9. func TestNats_server(t *testing.T) {
  10. opts := &server.Options{
  11. ServerName: "Yunlot-nats-server",
  12. Port: 6503,
  13. }
  14. // Initialize new server with options
  15. ns, err := server.NewServer(opts)
  16. if err != nil {
  17. panic(any(err))
  18. }
  19. // Start the server via goroutine
  20. go ns.Start()
  21. // Wait for server to be ready for connections
  22. if !ns.ReadyForConnections(4 * time.Second) {
  23. panic(any("not ready for connection"))
  24. }
  25. // Connect to server
  26. nc, err := nats.Connect(ns.ClientURL())
  27. if err != nil {
  28. panic(any(err))
  29. }
  30. subject := "my-subject"
  31. // Subscribe to the subject
  32. nc.Subscribe(subject, func(msg *nats.Msg) {
  33. // Print message data
  34. data := string(msg.Data)
  35. fmt.Println(data)
  36. // Shutdown the server (optional)
  37. ns.Shutdown()
  38. })
  39. // Publish data to the subject
  40. nc.Publish(subject, []byte("Hello embedded NATS!"))
  41. // Wait for server shutdown
  42. ns.WaitForShutdown()
  43. }