git.zd.zone/hrpc/hrpc@v0.0.12/server/server.go (about)

     1  package server
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"git.zd.zone/hrpc/hrpc/configs"
     7  	"git.zd.zone/hrpc/hrpc/option"
     8  	"git.zd.zone/hrpc/hrpc/utils/uniqueid"
     9  	"github.com/hashicorp/consul/api"
    10  	"google.golang.org/grpc"
    11  )
    12  
    13  var (
    14  	// env is the current environment
    15  	env = option.Development
    16  	// name is the name of server
    17  	name = ""
    18  )
    19  
    20  // Environment returns the current environment that the server is running for
    21  func Environment() option.Environment {
    22  	return env
    23  }
    24  
    25  // Name returns the name of this server
    26  func Name() string {
    27  	return name
    28  }
    29  
    30  // Server the server
    31  type Server interface {
    32  	// Server returns the gRPC server for registration at PB
    33  	Server() *grpc.Server
    34  	// Serve makes connections to databases and starts to listen ports to serve
    35  	// it will block the current thread
    36  	Serve() error
    37  	// Run same like Serve() but it does not register to consul and starts servers to block
    38  	// It will make connections to databases
    39  	Run() error
    40  }
    41  
    42  func registeration(id, name string, port int, tags []string, healthCheck bool) error {
    43  	reg := &api.AgentServiceRegistration{
    44  		ID:      id,
    45  		Name:    name,
    46  		Port:    port,
    47  		Tags:    tags,
    48  		Address: uniqueid.IP(),
    49  	}
    50  
    51  	if healthCheck {
    52  		reg.Check = &api.AgentServiceCheck{
    53  			HTTP:                           fmt.Sprintf("http://%s:6688", uniqueid.IP()),
    54  			Timeout:                        "3s",
    55  			Interval:                       "5s",
    56  			DeregisterCriticalServiceAfter: "30s",
    57  		}
    58  		// for health check
    59  		go func() {
    60  			defer func() {
    61  				if err := recover(); err != nil {
    62  					fmt.Println(err)
    63  				}
    64  			}()
    65  			runHealthAccepter()
    66  		}()
    67  	}
    68  	return configs.Client().Agent().ServiceRegister(reg)
    69  }
    70  
    71  func deregisteration(id string) error {
    72  	return configs.Client().Agent().ServiceDeregister(id)
    73  }