本文整理汇总了Golang中github.com/cloudfoundry/yagnats.NATSConn类的典型用法代码示例。如果您正苦于以下问题:Golang NATSConn类的具体用法?Golang NATSConn怎么用?Golang NATSConn使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了NATSConn类的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: connectToNatsServer
func connectToNatsServer(c *config.Config, logger *steno.Logger) yagnats.NATSConn {
var natsClient yagnats.NATSConn
var err error
natsServers := c.NatsServers()
attempts := 3
for attempts > 0 {
natsClient, err = yagnats.Connect(natsServers)
if err == nil {
break
} else {
attempts--
time.Sleep(100 * time.Millisecond)
}
}
if err != nil {
logger.Errorf("Error connecting to NATS: %s\n", err)
os.Exit(1)
}
natsClient.AddClosedCB(func(conn *nats.Conn) {
logger.Errorf("Close on NATS client. nats.Conn: %+v", *conn)
os.Exit(1)
})
return natsClient
}
示例2: NewStartStopListener
func NewStartStopListener(messageBus yagnats.NATSConn, conf *config.Config) *StartStopListener {
listener := &StartStopListener{
messageBus: messageBus,
}
messageBus.Subscribe(conf.SenderNatsStartSubject, func(message *nats.Msg) {
startMessage, err := models.NewStartMessageFromJSON([]byte(message.Data))
if err != nil {
panic(err)
}
listener.mutex.Lock()
listener.starts = append(listener.starts, startMessage)
listener.mutex.Unlock()
})
messageBus.Subscribe(conf.SenderNatsStopSubject, func(message *nats.Msg) {
stopMessage, err := models.NewStopMessageFromJSON([]byte(message.Data))
if err != nil {
panic(err)
}
listener.mutex.Lock()
listener.stops = append(listener.stops, stopMessage)
listener.mutex.Unlock()
})
return listener
}
示例3: connectToNatsServer
func connectToNatsServer(logger lager.Logger, c *config.Config) yagnats.NATSConn {
var natsClient yagnats.NATSConn
var err error
natsServers := c.NatsServers()
attempts := 3
for attempts > 0 {
natsClient, err = yagnats.Connect(natsServers)
if err == nil {
break
} else {
attempts--
time.Sleep(100 * time.Millisecond)
}
}
if err != nil {
logger.Fatal("nats-connection-error", err)
}
natsClient.AddClosedCB(func(conn *nats.Conn) {
logger.Fatal("nats-connection-closed", errors.New("unexpected close"), lager.Data{"connection": *conn})
})
return natsClient
}
示例4: Register
func (c *VcapComponent) Register(mbusClient yagnats.NATSConn) error {
mbusClient.Subscribe("vcap.component.discover", func(msg *nats.Msg) {
if msg.Reply == "" {
log.Warnf("Received message with empty reply on subject %s", msg.Subject)
return
}
c.Uptime = c.StartTime.Elapsed()
b, e := json.Marshal(c)
if e != nil {
log.Warnf(e.Error())
return
}
mbusClient.Publish(msg.Reply, b)
})
b, e := json.Marshal(c)
if e != nil {
log.Error(e.Error())
return e
}
mbusClient.Publish("vcap.component.announce", b)
log.Infof("Component %s registered successfully", c.Type)
return nil
}
示例5: StartFakeRouter
func StartFakeRouter() {
var startMessage = func() []byte {
d := RouterStart{
MinimumRegisterIntervalInSeconds: 20,
}
value, _ := json.Marshal(d)
return value
}
natsMembers := make([]string, 1)
uri := url.URL{
Scheme: "nats",
User: url.UserPassword("", ""),
Host: "127.0.0.1:4222",
}
natsMembers = append(natsMembers, uri.String())
var natsClient yagnats.NATSConn
var err error
for i := 0; i < 10; i++ {
natsClient, err = yagnats.Connect(natsMembers)
if err == nil {
break
}
time.Sleep(time.Second)
}
Expect(err).ToNot(HaveOccurred())
natsClient.Subscribe("router.register", func(msg *nats.Msg) {
})
natsClient.Subscribe("router.greet", func(msg *nats.Msg) {
natsClient.Publish(msg.Reply, startMessage())
})
natsClient.Publish("router.start", startMessage())
}
示例6:
"strings"
"time"
"github.com/cloudfoundry/gorouter/metrics/fakes"
"github.com/pivotal-golang/lager"
"github.com/pivotal-golang/lager/lagertest"
)
var _ = Describe("Router", func() {
var (
natsRunner *natsrunner.NATSRunner
natsPort uint16
config *cfg.Config
mbusClient yagnats.NATSConn
registry *rregistry.RouteRegistry
varz vvarz.Varz
router *Router
signals chan os.Signal
closeChannel chan struct{}
readyChan chan struct{}
logger lager.Logger
)
BeforeEach(func() {
natsPort = test_util.NextAvailPort()
natsRunner = natsrunner.NewNATSRunner(int(natsPort))
natsRunner.Start()
fakeEmitter := fake.NewFakeEventEmitter("fake")
dropsonde.InitializeWithEmitter(fakeEmitter)
示例7: main
func main() {
c := config.DefaultConfig()
logCounter := vcap.NewLogCounter()
if configFile != "" {
c = config.InitConfigFromFile(configFile)
}
InitLoggerFromConfig(c, logCounter)
logger := steno.NewLogger("router.main")
err := dropsonde.Initialize(c.Logging.MetronAddress, c.Logging.JobName)
if err != nil {
logger.Errorf("Dropsonde failed to initialize: %s", err.Error())
os.Exit(1)
}
// setup number of procs
if c.GoMaxProcs != 0 {
runtime.GOMAXPROCS(c.GoMaxProcs)
}
if c.DebugAddr != "" {
cf_debug_server.Run(c.DebugAddr)
}
natsServers := c.NatsServers()
var natsClient yagnats.NATSConn
attempts := 3
for attempts > 0 {
natsClient, err = yagnats.Connect(natsServers)
if err == nil {
break
} else {
attempts--
time.Sleep(100 * time.Millisecond)
}
}
if err != nil {
logger.Errorf("Error connecting to NATS: %s\n", err)
os.Exit(1)
}
natsClient.AddClosedCB(func(conn *nats.Conn) {
logger.Errorf("Close on NATS client. nats.Conn: %+v", *conn)
os.Exit(1)
})
registry := rregistry.NewRouteRegistry(c, natsClient)
if c.RoutingApiEnabled() {
logger.Info("Setting up routing_api route fetcher")
tokenFetcher := token_fetcher.NewTokenFetcher(&c.OAuth)
routingApiUri := fmt.Sprintf("%s:%d", c.RoutingApi.Uri, c.RoutingApi.Port)
routingApiClient := routing_api.NewClient(routingApiUri)
routeFetcher := route_fetcher.NewRouteFetcher(steno.NewLogger("router.route_fetcher"), tokenFetcher, registry, c, routingApiClient, 1)
routeFetcher.StartFetchCycle()
routeFetcher.StartEventCycle()
}
varz := rvarz.NewVarz(registry)
accessLogger, err := access_log.CreateRunningAccessLogger(c)
if err != nil {
logger.Fatalf("Error creating access logger: %s\n", err)
}
args := proxy.ProxyArgs{
EndpointTimeout: c.EndpointTimeout,
Ip: c.Ip,
TraceKey: c.TraceKey,
Registry: registry,
Reporter: varz,
AccessLogger: accessLogger,
SecureCookies: c.SecureCookies,
}
p := proxy.NewProxy(args)
router, err := router.NewRouter(c, p, natsClient, registry, varz, logCounter)
if err != nil {
logger.Errorf("An error occurred: %s", err.Error())
os.Exit(1)
}
signals := make(chan os.Signal, 1)
signal.Notify(signals, syscall.SIGTERM, syscall.SIGINT, syscall.SIGUSR1)
errChan := router.Run()
logger.Info("gorouter.started")
select {
case err := <-errChan:
if err != nil {
logger.Errorf("Error occurred: %s", err.Error())
os.Exit(1)
}
case sig := <-signals:
go func() {
//.........这里部分代码省略.........
示例8:
duration := stringMap["uptime"].(string)
Expect(duration).NotTo(Equal(`"uptime":"0d:0h:0m:0s"`))
})
It("returns 404 for non existent paths", func() {
serveComponent(component)
req := buildGetRequest(component, "/non-existent-path")
req.SetBasicAuth("username", "password")
code, _, _ := doGetRequest(req)
Expect(code).To(Equal(404))
})
Describe("Register", func() {
var mbusClient yagnats.NATSConn
var natsRunner *natsrunner.NATSRunner
var logger *gosteno.Logger
var sink *gosteno.TestingSink
BeforeEach(func() {
natsPort := test_util.NextAvailPort()
natsRunner = natsrunner.NewNATSRunner(int(natsPort))
natsRunner.Start()
mbusClient = natsRunner.MessageBus
sink = gosteno.NewTestingSink()
c := &gosteno.Config{
Sinks: []gosteno.Sink{
sink,
},
Level: gosteno.LOG_INFO,
示例9:
Expect(header.Get("Content-Type")).To(Equal("application/json"))
Expect(body).To(Equal(`{"key":"value"}` + "\n"))
})
It("returns 404 for non existent paths", func() {
serveComponent(component)
req := buildGetRequest(component, "/non-existent-path")
req.SetBasicAuth("username", "password")
code, _, _ := doGetRequest(req)
Expect(code).To(Equal(404))
})
Describe("Register", func() {
var mbusClient yagnats.NATSConn
var natsRunner *natsrunner.NATSRunner
var logger *gosteno.Logger
var sink *gosteno.TestingSink
BeforeEach(func() {
natsPort := test_util.NextAvailPort()
natsRunner = natsrunner.NewNATSRunner(int(natsPort))
natsRunner.Start()
mbusClient = natsRunner.MessageBus
sink = gosteno.NewTestingSink()
c := &gosteno.Config{
Sinks: []gosteno.Sink{
sink,
},
Level: gosteno.LOG_INFO,