示例#1
0
// Shows different ways to create a Conn
func ExampleConnect() {

	nats.Connect(nats.DefaultURL)
	nats.Connect("nats://*****:*****@nats.apcera.com:421")

	opts := nats.Options{
		AllowReconnect: true,
		MaxReconnect:   10,
		ReconnectWait:  5 * time.Second,
		Timeout:        1 * time.Second,
	}

	nc, _ := opts.Connect()
	nc.Close()
}
示例#2
0
func NewGnatsd(numberOfMessages int, testLatency bool) *Gnatsd {
	conn, _ := nats.Connect(nats.DefaultURL)

	// We want to be alerted if we get disconnected, this will
	// be due to Slow Consumer.
	conn.Opts.AllowReconnect = false

	// Report async errors.
	conn.Opts.AsyncErrorCB = func(nc *nats.Conn, sub *nats.Subscription, err error) {
		panic(fmt.Sprintf("NATS: Received an async error! %v\n", err))
	}

	// Report a disconnect scenario.
	conn.Opts.DisconnectedCB = func(nc *nats.Conn) {
		fmt.Printf("Getting behind! %d\n", nc.OutMsgs-nc.InMsgs)
		panic("NATS: Got disconnected!")
	}

	var handler benchmark.MessageHandler
	if testLatency {
		handler = &benchmark.LatencyMessageHandler{
			NumberOfMessages: numberOfMessages,
			Latencies:        []float32{},
		}
	} else {
		handler = &benchmark.ThroughputMessageHandler{NumberOfMessages: numberOfMessages}
	}

	return &Gnatsd{
		handler:     handler,
		subject:     "test",
		conn:        conn,
		testLatency: testLatency,
	}
}
示例#3
0
func ExampleConn_PublishMsg() {
	nc, _ := nats.Connect(nats.DefaultURL)
	defer nc.Close()

	msg := &nats.Msg{Subject: "foo", Reply: "bar", Data: []byte("Hello World!")}
	nc.PublishMsg(msg)
}
示例#4
0
文件: nats.go 项目: kgrvamsi/go-micro
func (n *ntport) Dial(addr string, opts ...transport.DialOption) (transport.Client, error) {
	cAddr := nats.DefaultURL

	if len(n.addrs) > 0 && strings.HasPrefix(n.addrs[0], "nats://") {
		cAddr = n.addrs[0]
	}

	c, err := nats.Connect(cAddr)
	if err != nil {
		return nil, err
	}

	id := nats.NewInbox()
	sub, err := c.SubscribeSync(id)
	if err != nil {
		return nil, err
	}

	return &ntportClient{
		conn: c,
		addr: addr,
		id:   id,
		sub:  sub,
	}, nil
}
示例#5
0
// This Example shows an asynchronous subscriber.
func ExampleConn_Subscribe() {
	nc, _ := nats.Connect(nats.DefaultURL)
	defer nc.Close()

	nc.Subscribe("foo", func(m *nats.Msg) {
		fmt.Printf("Received a message: %s\n", string(m.Data))
	})
}
示例#6
0
func ExampleSubscription_Unsubscribe() {
	nc, _ := nats.Connect(nats.DefaultURL)
	defer nc.Close()

	sub, _ := nc.SubscribeSync("foo")
	// ...
	sub.Unsubscribe()
}
示例#7
0
func ExampleConn_Request() {
	nc, _ := nats.Connect(nats.DefaultURL)
	defer nc.Close()

	nc.Subscribe("foo", func(m *nats.Msg) {
		nc.Publish(m.Reply, []byte("I will help you"))
	})
	nc.Request("foo", []byte("help"), 50*time.Millisecond)
}
示例#8
0
文件: bopen.go 项目: anykao/p
func main() {
	nc, _ := nats.Connect("nats://yourhost:4222")
	defer nc.Close()
	nc.QueueSubscribe(TOPIC, QUEUE, func(m *nats.Msg) {
		fmt.Println(string(m.Data))
		open.Start(string(m.Data))
	})
	select {}
}
示例#9
0
文件: bopen_linux.go 项目: anykao/p
func (b Bopen) Open(url string) {
	nc, _ := nats.Connect(nats.DefaultURL)
	defer nc.Close()
	if b.Topic != "" {
		nc.Publish(b.Topic, []byte(url))
	} else {
		nc.Publish("url", []byte(url))
	}
}
示例#10
0
func ExampleConn_QueueSubscribe() {
	nc, _ := nats.Connect(nats.DefaultURL)
	defer nc.Close()

	received := 0

	nc.QueueSubscribe("foo", "worker_group", func(_ *nats.Msg) {
		received += 1
	})
}
示例#11
0
func (nc *NatsClient) Init(server, service string) {
	var err error
	nc.natsConn, err = nats.Connect(server)
	if err != nil {
		panic(err)
	}
	nc.natsEnConn, err = nats.NewEncodedConn(nc.natsConn, nats.JSON_ENCODER)
	if err != nil {
		panic(err)
	}
	//defer ec.Close()
}
示例#12
0
func ExampleSubscription_NextMsg() {
	nc, _ := nats.Connect(nats.DefaultURL)
	defer nc.Close()

	sub, _ := nc.SubscribeSync("foo")
	m, err := sub.NextMsg(1 * time.Second)
	if err == nil {
		fmt.Printf("Received a message: %s\n", string(m.Data))
	} else {
		fmt.Println("NextMsg timed out.")
	}
}
示例#13
0
func ExampleConn_Flush() {
	nc, _ := nats.Connect(nats.DefaultURL)
	defer nc.Close()

	msg := &nats.Msg{Subject: "foo", Reply: "bar", Data: []byte("Hello World!")}
	for i := 0; i < 1000; i++ {
		nc.PublishMsg(msg)
	}
	err := nc.Flush()
	if err == nil {
		// Everything has been processed by the server for nc *Conn.
	}
}
示例#14
0
// EncodedConn can publish virtually anything just
// by passing it in. The encoder will be used to properly
// encode the raw Go type
func ExampleEncodedConn_Publish() {
	nc, _ := nats.Connect(nats.DefaultURL)
	c, _ := nats.NewEncodedConn(nc, "json")
	defer c.Close()

	type person struct {
		Name    string
		Address string
		Age     int
	}

	me := &person{Name: "derek", Age: 22, Address: "85 Second St"}
	c.Publish("hello", me)
}
示例#15
0
// BindSendChan() allows binding of a Go channel to a nats
// subject for publish operations. The Encoder attached to the
// EncodedConn will be used for marshalling.
func ExampleEncodedConn_BindSendChan() {
	nc, _ := nats.Connect(nats.DefaultURL)
	c, _ := nats.NewEncodedConn(nc, "json")
	defer c.Close()

	type person struct {
		Name    string
		Address string
		Age     int
	}

	ch := make(chan *person)
	c.BindSendChan("hello", ch)

	me := &person{Name: "derek", Age: 22, Address: "85 Second St"}
	ch <- me
}
示例#16
0
文件: nats.go 项目: kgrvamsi/go-micro
func (n *ntport) Listen(addr string) (transport.Listener, error) {
	cAddr := nats.DefaultURL

	if len(n.addrs) > 0 && strings.HasPrefix(n.addrs[0], "nats://") {
		cAddr = n.addrs[0]
	}

	c, err := nats.Connect(cAddr)
	if err != nil {
		return nil, err
	}

	return &ntportListener{
		addr: nats.NewInbox(),
		conn: c,
		exit: make(chan bool, 1),
	}, nil
}
示例#17
0
func ExampleSubscription_AutoUnsubscribe() {
	nc, _ := nats.Connect(nats.DefaultURL)
	defer nc.Close()

	received, wanted, total := 0, 10, 100

	sub, _ := nc.Subscribe("foo", func(_ *nats.Msg) {
		received += 1
	})
	sub.AutoUnsubscribe(wanted)

	for i := 0; i < total; i++ {
		nc.Publish("foo", []byte("Hello"))
	}
	nc.Flush()

	fmt.Printf("Received = %d", received)
}
示例#18
0
文件: nats.go 项目: bunin/Flotilla
// NewPeer creates and returns a new Peer for communicating with NATS.
func NewPeer(host string) (*Peer, error) {
	conn, err := nats.Connect(fmt.Sprintf("nats://%s", host))
	if err != nil {
		return nil, err
	}

	// We want to be alerted if we get disconnected, this will be due to Slow
	// Consumer.
	conn.Opts.AllowReconnect = false

	return &Peer{
		conn:     conn,
		messages: make(chan []byte, 10000),
		send:     make(chan []byte),
		errors:   make(chan error, 1),
		done:     make(chan bool),
	}, nil
}
示例#19
0
func init() {
	cfgPtr := flag.String("config", "config/director.json", "Path to the config file")
	flag.Parse()

	f, err := os.Open(*cfgPtr)
	if err != nil {
		fmt.Println("Cannot open the config file:", err)
		os.Exit(1)
	}

	err = json.NewDecoder(f).Decode(&cfg)
	if err != nil {
		fmt.Println("Cannot decode the config file:", err)
		os.Exit(1)
	}

	db_dsn := cfg.DB["Username"] + ":" + cfg.DB["Password"] + "@tcp(" + cfg.DB["Host"] + ":" + cfg.DB["Port"] + ")/" + cfg.DB["Database"]
	db, err = sql.Open("mysql", db_dsn)
	if err != nil {
		fmt.Println("Cannot connect to the Policy database:", err)
		os.Exit(1)
	}

	if cfg.Duration != 0 {
		duration = cfg.Duration
	}

	natsc, err = nats.Connect(cfg.Nats)
	if err != nil {
		fmt.Println("Cannot connect to the gnatsd:", err)
		os.Exit(1)
	}

	if cfg.Log != "" {
		logf, err := os.Open(cfg.Log)
		if err != nil {
			fmt.Println("Cannot open the log file:", err)
			os.Exit(1)
		}
		log.SetOutput(logf)
	}
}
示例#20
0
文件: nats.go 项目: adfin/gocelery
// Connect to rabbitmq
func (b *Broker) Connect(uri string) error {
	b.natsURL = uri
	log.Debugf("Dialing [%s]", uri)

	// dial the server
	conn, err := nats.Connect(b.natsURL)
	if err != nil {
		return err
	}

	// create the encoded connection
	b.connection, err = nats.NewEncodedConn(conn, "json")
	if err != nil {
		return err
	}

	log.Debug("Connected to gnatsd")

	return nil
}
示例#21
0
文件: main.go 项目: carriercomm/api-1
func main() {
	nc, err := nats.Connect("nats://127.0.0.1:4222")
	if err != nil {
		log.Fatal(err)
	}

	c, err := nats.NewEncodedConn(nc, "json")
	if err != nil {
		log.Fatal(err)
	}

	c.Publish("receipt", &struct {
		ID    string `json:"id"`
		Owner string `json:"owner"`
	}{
		ID:    "helloworld",
		Owner: "k5TuCXomSMEeCdXw1aXl",
	})

	log.Print("x")
}
示例#22
0
func main() {
	http.HandleFunc("/echo", func(w http.ResponseWriter, req *http.Request) {
		nc, err := nats.Connect(os.Getenv("NATS_URI"))
		if err != nil {
			http.Error(w,
				fmt.Sprintf("Error connecting to NATS at %q: %s\n", os.Getenv("NATS_URI"), err),
				http.StatusInternalServerError)
			return
		}
		defer nc.Close()

		msg := req.FormValue("msg")

		sub, err := nc.Subscribe("test", func(m *nats.Msg) {
			nc.Publish(m.Reply, []byte(msg))
		})
		if err != nil {
			http.Error(w,
				fmt.Sprintf("Can't subscribe to 'test' subject: %s\n", err),
				http.StatusInternalServerError)
			return
		}
		defer sub.Unsubscribe()

		reply, err := nc.Request("test", []byte(msg), time.Second)
		if err != nil {
			http.Error(w,
				fmt.Sprintf("Request failed: %s\n", err),
				http.StatusInternalServerError)
			return
		}

		fmt.Fprintf(w, string(reply.Data)+"\n")
	})

	err := http.ListenAndServe(":"+os.Getenv("PORT"), nil)
	if err != nil {
		log.Fatal("Error starting HTTP server: ", err)
	}
}
示例#23
0
// BindRecvChan() allows binding of a Go channel to a nats
// subject for subscribe operations. The Encoder attached to the
// EncodedConn will be used for un-marshalling.
func ExampleEncodedConn_BindRecvChan() {
	nc, _ := nats.Connect(nats.DefaultURL)
	c, _ := nats.NewEncodedConn(nc, "json")
	defer c.Close()

	type person struct {
		Name    string
		Address string
		Age     int
	}

	ch := make(chan *person)
	c.BindRecvChan("hello", ch)

	me := &person{Name: "derek", Age: 22, Address: "85 Second St"}
	c.Publish("hello", me)

	// Receive the publish directly on a channel
	who := <-ch

	fmt.Printf("%v says hello!\n", who)
}
示例#24
0
func (n *NATS) InitBus(config interface{}) error {
	var err error
	c := config.(map[string]interface{})
	for key, value := range c {
		switch key {
		case "url":
			n.config.URL = value.(string)
		case "queue":
			n.config.Queue = value.(string)
		}
	}

	n.connection, err = nats.Connect(n.config.URL)
	if err != nil {
		return err
	}
	n.encoder, err = nats.NewEncodedConn(n.connection, "default")
	if err != nil {
		return err
	}
	return nil
}
示例#25
0
// EncodedConn's subscribers will automatically decode the
// wire data into the requested Go type using the Decode()
// method of the registered Encoder. The callback signature
// can also vary to include additional data, such as subject
// and reply subjects.
func ExampleEncodedConn_Subscribe() {
	nc, _ := nats.Connect(nats.DefaultURL)
	c, _ := nats.NewEncodedConn(nc, "json")
	defer c.Close()

	type person struct {
		Name    string
		Address string
		Age     int
	}

	c.Subscribe("hello", func(p *person) {
		fmt.Printf("Received a person! %+v\n", p)
	})

	c.Subscribe("hello", func(subj, reply string, p *person) {
		fmt.Printf("Received a person on subject %s! %+v\n", subj, p)
	})

	me := &person{Name: "derek", Age: 22, Address: "85 Second St"}
	c.Publish("hello", me)
}
示例#26
0
func init() {
	cfgPtr := flag.String("config", "config/engine.json", "Path to the config file")
	flag.Parse()

	f, err := os.Open(*cfgPtr)
	if err != nil {
		fmt.Println("Cannot open the config file:", err)
		os.Exit(1)
	}

	err = json.NewDecoder(f).Decode(&cfg)
	if err != nil {
		fmt.Println("Cannot decode the config file:", err)
		os.Exit(1)
	}

	ccc = CCClient{
		api_host:  cfg.CloudController["Api_host"],
		auth_host: cfg.CloudController["Auth_host"],
		auth_user: cfg.CloudController["Auth_user"],
		auth_pass: cfg.CloudController["Auth_pass"]}

	natsc, err = nats.Connect(cfg.Nats)
	if err != nil {
		fmt.Println("Cannot connect to the gnatsd:", err)
		os.Exit(1)
	} else {
		fmt.Println("Connected to the nats server:", cfg.Nats)
	}

	if cfg.Log != "" {
		logf, err := os.Open(cfg.Log)
		if err != nil {
			fmt.Println("Cannot open the log file:", err)
			os.Exit(1)
		}
		log.SetOutput(logf)
	}
}
示例#27
0
func init() {
	cfgPtr := flag.String("config", "config/avger.json", "Path to the config file")
	flag.Parse()

	f, err := os.Open(*cfgPtr)
	if err != nil {
		fmt.Println("Cannot open the config file:", err)
		os.Exit(1)
	}

	err = json.NewDecoder(f).Decode(&cfg)
	if err != nil {
		fmt.Println("Cannot decode the config file:", err)
		os.Exit(1)
	}

	natsc, err = nats.Connect(cfg.Nats)
	if err != nil {
		fmt.Println("Cannot connect to the gnatsd:", err)
		os.Exit(1)
	}

	var avger Avger

	// // MetricDB connection
	// mdb_dsn :=  cfg.MetricDB["Username"]+":"+
	//             cfg.MetricDB["Password"]+"@tcp("+
	//             cfg.MetricDB["Host"]+":"+
	//             cfg.MetricDB["Port"]+")/"+
	//             cfg.MetricDB["Database"]
	// mdb_conn, err = sql.Open("mysql", mdb_dsn)
	// if err != nil {
	//     fmt.Println("Cannot connect to the Policy database:", err)
	//     os.Exit(1)
	// }
	// mdb = MetricDB {db: mdb_conn}
}
示例#28
0
func ExampleConn_Close() {
	nc, _ := nats.Connect(nats.DefaultURL)
	nc.Close()
}
示例#29
0
// Shows how to wrap a Conn into an EncodedConn
func ExampleNewEncodedConn() {
	nc, _ := nats.Connect(nats.DefaultURL)
	c, _ := nats.NewEncodedConn(nc, "json")
	c.Close()
}
示例#30
0
func ExampleConn_Publish() {
	nc, _ := nats.Connect(nats.DefaultURL)
	defer nc.Close()

	nc.Publish("foo", []byte("Hello World!"))
}