go-nsq Documentation
repository·master·Indexed 25 days ago
https://github.com/nsqio/go-nsqThe official Go client library for NSQ, a distributed real-time messaging platform. go-nsq provides the necessary implementations for Go developers to build producers and consumers that integrate with NSQ nodes, including support for message publishing, subscription management, and connection handling.
What's inside go-nsq
- go-nsq is the official Go package for interacting with [NSQ][nsq]. It provides the necessary client implementations to build applications that produce or consume messages within the NSQ ecosystem.
Run tests for go-nsq
masterTo run the project tests, use the provided
test.shscript. Note that this requiresnsqdandnsqlookupdto be installed and available in your environment../test.shInitialize NSQ configuration with NewConfig
masterTo create a new NSQ configuration, you must use theNewConfig()function. Using a struct literal forConfigwill cause a panic. Once aConfigobject is passed into a high-level type (like aConsumerorProducer), its values are copied and are no longer mutable. You can modify the configuration before passing it to these types by setting fields directly or using theSet()method.Configure TLS settings
masterYou can configure TLS for your NSQ client using specific
tls_*options via theSet()method. These options modify the underlyingTlsConfigfield.Available TLS Options:
tls_v1: Boolean to enable TLS negotiation.tls_root_ca_file: String path to a file containing the root CA.tls_insecure_skip_verify: Boolean indicating whether to verify server certificates.tls_cert: String path to the public key certificate file.tls_key: String path to the private key file.tls_min_version: String indicating the minimum TLS version:'ssl3.0','tls1.0','tls1.1', or'tls1.2'.
Configure logging for a Conn instance
masterYou can assign a custom logger to a
Conninstance usingSetLogger. The logger must implement theloggerinterface, which requires anOutput(calldepth int, s string)method (the standard librarylog.Loggersatisfies this).You can also set the logging level or specify a custom format string. The format string should be a
printf-compatible string with a single%sargument used for the connection address.Serialize and Deserialize Messages
masterMessages can be serialized to an
io.Writeror deserialized from a byte slice using the following methods:WriteTo(w io.Writer): Serializes the message (Timestamp, Attempts, ID, and Body) into the provided writer. It is recommended to use a buffered writer to minimize system calls.DecodeMessage(b []byte): Deserializes a byte slice into a*Message. The expected wire format is: 8-byte nanosecond timestamp, 2-byte attempts, 16-byte ASCII hex encoded ID, and the N-byte body.
Add concurrent message handlers
masterTo increase processing throughput, use
AddConcurrentHandlersto spawn multiple goroutines for message handling. Theconcurrencyparameter determines the number of goroutines.Warning: This method panics if called after the consumer has already connected to an
nsqdornsqlookupdinstance.Handle connection lifecycle and state
masterThe
Conntype provides methods to monitor the connection state and RDY counts:Close(): Idempotently initiates a graceful connection close.IsClosing(): Returnstrueif the connection is currently in the process of closing.RDY(): Returns the current RDY count.MaxRDY(): Returns the maximum RDY count negotiated withnsqd.LastRDY(): Returns the previously set RDY count.LastRdyTime(): Returns the time of the last non-zero RDY update.LastMessageTime(): Returns the time the last message was received.RemoteAddr(): Returns the destinationnsqdaddress.
Adjust Max In-Flight messages dynamically
masterUse
ChangeMaxInFlight(maxInFlight int)to update the maximum number of messages the consumer instance is allowed to have in-flight across all connections.Setting
ChangeMaxInFlight(0)will effectively pause the flow of messages to the consumer.Publish multiple messages asynchronously with Producer.MultiPublishAsync
masterUseMultiPublishAsyncto send a slice of message bodies without waiting for thensqdresponse. Similar toPublishAsync, you can provide adoneChanto receive a*ProducerTransactiononce the operation completes.Publish messages synchronously with Producer.Publish
masterUsePublishto synchronously send a single message body to a specific topic. This method blocks until the message is successfully published or an error is returned.Configure Producer logging
masterThe
Producerallows custom logging via theSetLogger,SetLoggerForLevel, andSetLoggerLevelmethods. The logger must implement the following interface:type logger interface { Output(calldepth int, s string) }SetLogger(l logger, lvl LogLevel): Sets the same logger for all log levels.SetLoggerForLevel(l logger, lvl LogLevel): Sets a specific logger for a specificLogLevel.SetLoggerLevel(lvl LogLevel): Sets the global package logging level.