Esempio n. 1
0
func (router *Router) Run() {
	var err error

	for {
		err = router.mbusClient.Connect()
		if err == nil {
			break
		}
		log.Errorf("Could not connect to NATS: ", err.Error())
		time.Sleep(500 * time.Millisecond)
	}

	router.mbusClient.OnConnect(func() {
		router.SendStartMessage()
	})

	router.RegisterComponent()

	// Subscribe register/unregister router
	router.SubscribeRegister()
	router.HandleGreetings()
	router.SubscribeUnregister()

	// Kickstart sending start messages
	router.SendStartMessage()

	// Schedule flushing active app's app_id
	router.ScheduleFlushApps()

	// Wait for one start message send interval, such that the router's registry
	// can be populated before serving requests.
	if router.config.StartResponseDelayInterval != 0 {
		log.Infof("Waiting %s before listening...", router.config.StartResponseDelayInterval)
		time.Sleep(router.config.StartResponseDelayInterval)
	}

	listen, err := net.Listen("tcp", fmt.Sprintf(":%d", router.config.Port))
	if err != nil {
		log.Fatalf("net.Listen: %s", err)
	}

	util.WritePidFile(router.config.Pidfile)

	log.Infof("Listening on %s", listen.Addr())

	server := proxy.Server{Handler: router.proxy}

	err = server.Serve(listen)
	if err != nil {
		log.Fatalf("proxy.Serve: %s", err)
	}
}
Esempio n. 2
0
func (r *Router) Run() {
	var err error

	natsMembers := []yagnats.ConnectionProvider{}

	for _, info := range r.config.Nats {
		natsMembers = append(natsMembers, &yagnats.ConnectionInfo{
			Addr:     fmt.Sprintf("%s:%d", info.Host, info.Port),
			Username: info.User,
			Password: info.Pass,
		})
	}

	natsInfo := &yagnats.ConnectionCluster{natsMembers}

	for {
		err = r.mbusClient.Connect(natsInfo)

		if err == nil {
			break
		}

		log.Errorf("Could not connect to NATS: %s", err)
		time.Sleep(500 * time.Millisecond)
	}

	r.RegisterComponent()

	// Subscribe register/unregister router
	r.SubscribeRegister()
	r.HandleGreetings()
	r.SubscribeUnregister()

	// Kickstart sending start messages
	r.SendStartMessage()

	// Send start again on reconnect
	r.mbusClient.ConnectedCallback = func() {
		r.SendStartMessage()
	}

	// Schedule flushing active app's app_id
	r.ScheduleFlushApps()

	// Wait for one start message send interval, such that the router's registry
	// can be populated before serving requests.
	if r.config.StartResponseDelayInterval != 0 {
		log.Infof("Waiting %s before listening...", r.config.StartResponseDelayInterval)
		time.Sleep(r.config.StartResponseDelayInterval)
	}

	listen, err := net.Listen("tcp", fmt.Sprintf(":%d", r.config.Port))
	if err != nil {
		log.Fatalf("net.Listen: %s", err)
	}

	util.WritePidFile(r.config.Pidfile)

	log.Infof("Listening on %s", listen.Addr())

	server := http.Server{Handler: r.proxy}

	go func() {
		err := server.Serve(listen)
		if err != nil {
			log.Fatalf("proxy.Serve: %s", err)
		}
	}()
}