Пример #1
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()
}
Пример #2
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)
}
Пример #3
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
}
Пример #4
0
// ConnectNatsQueue connects the application to the Gnatsd cluster.
func ConnectNatsQueue(servers []string, d db.Connection) queue.Connection {
	opts := nats.DefaultOptions
	opts.Servers = servers

	nc, err := opts.Connect()
	if err != nil {
		log.Fatalf("Unable to connect to the Gnatsd servers: %v\n", err)
	}

	ec, err := nats.NewEncodedConn(nc, "json")
	if err != nil {
		log.Fatalf("Unable to encode the connection for json messages: %v\n", err)
	}

	log.Printf("Connected to Gnatsd cluster in %v\n", servers)

	return queue.NewNatsConn(d, ec)
}
Пример #5
0
// 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
}
Пример #6
0
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")
}
Пример #7
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
}
Пример #8
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)
}
Пример #9
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)
}
// This will test queue subscriber semantics across a cluster in the presence
// of server restarts.
func TestServerRestartAndQueueSubs(t *testing.T) {
	srvA, srvB, optsA, optsB := runServers(t)

	urlA := fmt.Sprintf("nats://%s:%d/", optsA.Host, optsA.Port)
	urlB := fmt.Sprintf("nats://%s:%d/", optsB.Host, optsB.Port)

	// Client options
	opts := nats.DefaultOptions
	opts.Timeout = (5 * time.Second)
	opts.ReconnectWait = (50 * time.Millisecond)
	opts.MaxReconnect = 1000
	opts.NoRandomize = true

	// Allow us to block on a reconnect completion.
	reconnectsDone := make(chan bool)
	opts.ReconnectedCB = func(nc *nats.Conn) {
		reconnectsDone <- true
	}

	// Helper to wait on a reconnect.
	waitOnReconnect := func() {
		var rcs int64
		for {
			select {
			case <-reconnectsDone:
				atomic.AddInt64(&rcs, 1)
				if rcs >= 2 {
					return
				}
			case <-time.After(2 * time.Second):
				t.Fatalf("Expected a reconnect, timedout!\n")
			}
		}
	}

	// Create two clients..
	opts.Servers = []string{urlA}
	nc1, err := opts.Connect()
	if err != nil {
		t.Fatalf("Failed to create connection for nc1: %v\n", err)
	}

	opts.Servers = []string{urlB}
	nc2, err := opts.Connect()
	if err != nil {
		t.Fatalf("Failed to create connection for nc2: %v\n", err)
	}

	c1, _ := nats.NewEncodedConn(nc1, "json")
	defer c1.Close()
	c2, _ := nats.NewEncodedConn(nc2, "json")
	defer c2.Close()

	// Flusher helper function.
	flush := func() {
		// Wait for processing.
		c1.Flush()
		c2.Flush()
		// Wait for a short bit for cluster propogation.
		time.Sleep(50 * time.Millisecond)
	}

	// To hold queue results.
	results := make(map[int]int)
	var mu sync.Mutex

	// This corresponds to the subsriptions below.
	const ExpectedMsgCount = 3

	// Make sure we got what we needed, 1 msg only and all seqnos accounted for..
	checkResults := func(numSent int) {
		mu.Lock()
		defer mu.Unlock()

		for i := 0; i < numSent; i++ {
			if results[i] != ExpectedMsgCount {
				t.Fatalf("Received incorrect number of messages, [%d] for seq: %d\n", results[i], i)
			}
		}

		// Auto reset results map
		results = make(map[int]int)
	}

	subj := "foo.bar"
	qgroup := "workers"

	cb := func(seqno int) {
		mu.Lock()
		defer mu.Unlock()
		results[seqno] = results[seqno] + 1
	}

	// Create queue subscribers
	c1.QueueSubscribe(subj, qgroup, cb)
	c2.QueueSubscribe(subj, qgroup, cb)

	// Do a wildcard subscription.
	c1.Subscribe("foo.*", cb)
	c2.Subscribe("foo.*", cb)

	// Wait for processing.
	flush()

	sendAndCheckMsgs := func(numToSend int) {
		for i := 0; i < numToSend; i++ {
			if i%2 == 0 {
				c1.Publish(subj, i)
			} else {
				c2.Publish(subj, i)
			}
		}
		// Wait for processing.
		flush()
		// Check Results
		checkResults(numToSend)
	}

	////////////////////////////////////////////////////////////////////////////
	// Base Test
	////////////////////////////////////////////////////////////////////////////

	// Now send 10 messages, from each client..
	sendAndCheckMsgs(10)

	////////////////////////////////////////////////////////////////////////////
	// Now restart SrvA and srvB, re-run test
	////////////////////////////////////////////////////////////////////////////

	srvA.Shutdown()
	srvA = RunServer(optsA)
	defer srvA.Shutdown()

	srvB.Shutdown()
	srvB = RunServer(optsB)
	defer srvB.Shutdown()

	waitOnReconnect()

	time.Sleep(50 * time.Millisecond)

	// Now send another 10 messages, from each client..
	sendAndCheckMsgs(10)
}
Пример #11
0
// Shows how to wrap a Conn into an EncodedConn
func ExampleNewEncodedConn() {
	nc, _ := nats.Connect(nats.DefaultURL)
	c, _ := nats.NewEncodedConn(nc, "json")
	c.Close()
}
Пример #12
0
func main() {
	// create session store
	store := sessions.NewCookieStore([]byte("nRrHLlHcHH0u7fUz25Hje9m7uJ5SnJzP"))

	// store options
	store.Options = &sessions.Options{
		Path:   "/",
		Domain: "aaronstgeorge.co",
		MaxAge: 0,
	}

	// open database connection
	db, err := sql.Open("mysql", "root:@/Tanks")
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()
	// test connection
	err = db.Ping()
	if err != nil {
		log.Fatal(err)
	}

	// create connection to nats server
	nc, _ := nats.Connect(nats.DefaultURL)
	ec, _ := nats.NewEncodedConn(nc, "json")
	defer ec.Close()

	global := &Global{db: db, store: store, ec: ec}

	stdChain := alice.New(global.loadSession)
	loadUser := stdChain.Append(global.loadUser)
	loadUserData := loadUser.Append(global.loadFriends)

	router := httprouter.New()

	// mainPage
	router.Handler("GET", "/", loadUserData.Then(http.HandlerFunc(mainPage)))

	// login
	router.HandlerFunc("GET", "/login", loginGET)
	router.Handler("POST", "/login", stdChain.Then(
		http.HandlerFunc(global.loginPOST)))

	// logout
	router.Handler("GET", "/logout", stdChain.Then(http.HandlerFunc(logout)))

	// play
	router.HandlerFunc("GET", "/play", http.HandlerFunc(play))

	// game websocket
	router.Handler("GET", "/gpws", loadUser.Then(http.HandlerFunc(
		global.gamePageWs)))

	// mainPage websocket
	router.Handler("GET", "/mpws", loadUserData.Then(http.HandlerFunc(
		global.mainPageWs)))

	// register
	router.HandlerFunc("GET", "/register", registerGET)
	router.Handler("POST", "/register", stdChain.Then(
		http.HandlerFunc(global.registerPOST)))

	// add friend
	router.HandlerFunc("GET", "/friend", friendGET)
	router.Handler("POST", "/friend", loadUser.Then(
		http.HandlerFunc(global.friendPOST)))

	// Serve static files from the ./public directory
	router.ServeFiles("/static/*filepath", http.Dir("./public/"))

	fmt.Println("serving...")
	log.Fatal(http.ListenAndServe(":80", context.ClearHandler(router)))
}
Пример #13
0
func main() {
	var urls = flag.String("s", "", "The NATS server URL(s) (separated by comma)")
	var delay = flag.Float64("d", 2.0, "Delay represented as fractional seconds")
	var help = flag.Bool("h", false, "Display usage")

	log.SetFlags(0)
	flag.Usage = usage
	flag.Parse()

	if *help {
		usage()
	}

	opts := nats.DefaultOptions

	// Process servers to connect to..
	if *urls == "" {
		// Check env for NATS_URI
		if nuri := os.Getenv("NATS_URI"); nuri != "" {
			*urls = nuri
		} else {
			*urls = nats.DefaultURL
		}
	}
	opts.Servers = strings.Split(*urls, ",")
	for i, s := range opts.Servers {
		opts.Servers[i] = strings.Trim(s, " ")
	}

	// Setup the event hooks to be notified on
	// disconnect and reconnect events.
	opts.ReconnectedCB = func(nc *nats.Conn) {
		log.Printf("[EVENT] Reconnected to %s [ID:%s]\n",
			nc.ConnectedUrl(), nc.ConnectedServerId())
	}

	opts.DisconnectedCB = func(nc *nats.Conn) {
		log.Printf("[EVENT] Got disconnected\n")
	}

	opts.ClosedCB = func(nc *nats.Conn) {
		log.Fatalf("[EVENT] Connection closed!\n")
	}

	// Connect and setup encoded connection.
	nc, err := opts.Connect()
	if err != nil {
		log.Fatalf("[ERR] Can't connect to server: %v\n", err)
	}

	log.Printf("[EVENT] Connected to %s [ID:%s]\n",
		nc.ConnectedUrl(), nc.ConnectedServerId())

	ec, err := nats.NewEncodedConn(nc, nats.JSON_ENCODER)
	if err != nil {
		log.Fatalf("Can't create encoded connection: %v\n", err)
	}

	// Calculate delay
	delayTime := time.Duration(*delay * float64(time.Second))
	log.Printf("[INFO] Delay is %v\n", delayTime)

	// Setup our listener to the pings.
	ec.Subscribe(PING, func(sent time.Time) {
		log.Printf("[PING] Latency: %v\n", time.Since(sent))
	})

	// Loop, publishing our ping after delay seconds.
	for {
		ec.Publish(PING, time.Now())
		time.Sleep(delayTime)
	}
}