github.com/ronaksoft/rony@v0.16.26-0.20230807065236-1743dbfe6959/example/redirect/cmd/cli-redirect/cmd_server.go (about)

     1  package main
     2  
     3  import (
     4  	"os"
     5  	"runtime"
     6  	"time"
     7  
     8  	"github.com/ronaksoft/rony"
     9  	"github.com/ronaksoft/rony/config"
    10  	"github.com/ronaksoft/rony/edge"
    11  	"github.com/ronaksoft/rony/errors"
    12  	"github.com/ronaksoft/rony/example/redirect/rpc"
    13  	"github.com/spf13/cobra"
    14  )
    15  
    16  var edgeServer *edge.Server
    17  
    18  var ServerCmd = &cobra.Command{
    19  	Use: "server",
    20  	RunE: func(cmd *cobra.Command, args []string) error {
    21  		err := config.BindCmdFlags(cmd)
    22  		if err != nil {
    23  			return errors.WrapText("bind flag:")(err)
    24  		}
    25  
    26  		// Instantiate the edge server
    27  		edgeServer = edge.NewServer(
    28  			config.GetString("server.id"),
    29  			edge.WithTcpGateway(edge.TcpGatewayConfig{
    30  				Concurrency:   runtime.NumCPU() * 100,
    31  				ListenAddress: config.GetString("gateway.listen"),
    32  				MaxIdleTime:   config.GetDuration("idle-time"),
    33  				Protocol:      rony.TCP,
    34  				ExternalAddrs: config.GetStringSlice("gateway.advertise.url"),
    35  			}),
    36  			edge.WithGossipCluster(edge.GossipClusterConfig{
    37  				Bootstrap:  config.GetBool("bootstrap"),
    38  				ReplicaSet: config.GetUint64("replica-set"),
    39  				GossipPort: config.GetInt("gossip.port"),
    40  			}),
    41  			edge.WithUdpTunnel(edge.UdpTunnelConfig{
    42  				ListenAddress: config.GetString("tunnel.listen"),
    43  				ExternalAddrs: config.GetStringSlice("tunnel.advertise.url"),
    44  			}),
    45  		)
    46  
    47  		// Register the implemented service into the edge server
    48  		rpc.RegisterSample(&rpc.Sample{}, edgeServer)
    49  
    50  		// Start the edge server components
    51  		edgeServer.Start()
    52  
    53  		time.Sleep(time.Second * 3)
    54  
    55  		if config.GetString("seed") != "" {
    56  			n, err := edgeServer.Cluster().Join(config.GetString("seed"))
    57  			if err != nil {
    58  				cmd.Println("Error On Joining Cluster:", err)
    59  			} else {
    60  				cmd.Println("Joined", config.GetString("seed"), n)
    61  			}
    62  		}
    63  
    64  		// Wait until a shutdown signal received.
    65  		edgeServer.WaitForSignal(os.Kill, os.Interrupt)
    66  		_ = edgeServer.Cluster().Leave()
    67  		edgeServer.Shutdown()
    68  
    69  		return nil
    70  	},
    71  }