Last active
November 28, 2021 20:35
-
-
Save blinkinglight/e0359b830925fad9694cf6467fb89a2e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"log" | |
"runtime" | |
"time" | |
"github.com/nats-io/nats.go" | |
"github.com/nats-io/stan.go" | |
) | |
var err error | |
var sc stan.Conn | |
var cch = make(chan struct{}, 1) | |
var ch = make(chan struct{}, 1) | |
func main() { | |
go func() { | |
ch <- struct{}{} | |
for { | |
time.Sleep(time.Second) | |
select { | |
case <-ch: | |
log.Printf("connecting") | |
sc, err = stan.Connect("1", "2", stan.Pings(1, 3), stan.SetConnectionLostHandler(func(c stan.Conn, e error) { | |
log.Printf("dizconnected") | |
ch <- struct{}{} | |
}), stan.ConnectWait(time.Second), stan.NatsURL("nats://192.168.1.243:4222"), stan.NatsOptions(nats.MaxReconnects(1<<31), nats.ReconnectWait(time.Second)), stan.AllowCloseRetry(true)) | |
if err != nil { | |
log.Printf("%v", err) | |
ch <- struct{}{} | |
log.Printf("%v", "reconnecting....") | |
continue | |
} | |
sc.Subscribe("test", func(msg *stan.Msg) { | |
log.Printf("%s", msg.Data) | |
if string(msg.Data) == "disconnect" { | |
log.Printf("%v", "disconnecting....") | |
cch <- struct{}{} | |
} | |
}, stan.DurableName("stan2")) | |
case <-cch: | |
ch <- struct{}{} | |
sc.Close() | |
time.Sleep(time.Second * 3) | |
log.Printf("%v", "disconnected") | |
default: | |
} | |
} | |
}() | |
runtime.Goexit() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment