本文整理汇总了Golang中google/golang.org/grpc.Server.Serve方法的典型用法代码示例。如果您正苦于以下问题:Golang Server.Serve方法的具体用法?Golang Server.Serve怎么用?Golang Server.Serve使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类google/golang.org/grpc.Server
的用法示例。
在下文中一共展示了Server.Serve方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: serveGRPC
func serveGRPC(server *grpc.Server, l net.Listener) {
defer l.Close()
if err := server.Serve(l); err != nil {
l.Close()
logrus.WithError(err).Fatal("containerd: GRPC server failure")
}
}
示例2: setUpSignerClient
func setUpSignerClient(t *testing.T, grpcServer *grpc.Server) (*client.NotarySigner, *grpc.ClientConn, func()) {
socketFile, err := ioutil.TempFile("", "notary-grpc-test")
require.NoError(t, err)
socketFile.Close()
os.Remove(socketFile.Name())
lis, err := net.Listen("unix", socketFile.Name())
require.NoError(t, err, "unable to open socket to listen")
go grpcServer.Serve(lis)
// client setup
clientConn, err := grpc.Dial(socketFile.Name(), grpc.WithInsecure(), grpc.WithDialer(socketDialer))
require.NoError(t, err, "unable to connect to socket as a GRPC client")
signerClient := client.NewNotarySigner(clientConn)
cleanup := func() {
clientConn.Close()
grpcServer.Stop()
os.Remove(socketFile.Name())
}
return signerClient, clientConn, cleanup
}
示例3: startGRPC
func startGRPC(srv *grpc.Server) {
l, err := net.Listen("tcp", *grpcListeningAddr)
if err != nil {
log.Fatalf("Error listening on GRPC address %q: %v", *grpcListeningAddr, err)
}
log.Printf("GRPC server listening on %s", l.Addr())
log.Fatal(srv.Serve(l))
}
示例4: NewCommInstanceWithServer
// NewCommInstanceWithServer creates a comm instance that creates an underlying gRPC server
func NewCommInstanceWithServer(port int, idMapper identity.Mapper, peerIdentity api.PeerIdentityType, dialOpts ...grpc.DialOption) (Comm, error) {
var ll net.Listener
var s *grpc.Server
var secOpt grpc.DialOption
if len(dialOpts) == 0 {
dialOpts = []grpc.DialOption{grpc.WithTimeout(dialTimeout)}
}
if port > 0 {
s, ll, secOpt = createGRPCLayer(port)
dialOpts = append(dialOpts, secOpt)
}
commInst := &commImpl{
PKIID: idMapper.GetPKIidOfCert(peerIdentity),
idMapper: idMapper,
logger: util.GetLogger(util.LOGGING_COMM_MODULE, fmt.Sprintf("%d", port)),
peerIdentity: peerIdentity,
opts: dialOpts,
port: port,
lsnr: ll,
gSrv: s,
msgPublisher: NewChannelDemultiplexer(),
lock: &sync.RWMutex{},
deadEndpoints: make(chan common.PKIidType, 100),
stopping: int32(0),
exitChan: make(chan struct{}, 1),
subscriptions: make([]chan ReceivedMessage, 0),
blackListedPKIIDs: make([]common.PKIidType, 0),
}
commInst.connStore = newConnStore(commInst, commInst.logger)
commInst.idMapper.Put(idMapper.GetPKIidOfCert(peerIdentity), peerIdentity)
if port > 0 {
go func() {
commInst.stopWG.Add(1)
defer commInst.stopWG.Done()
s.Serve(ll)
}()
proto.RegisterGossipServer(s, commInst)
}
commInst.logger.SetLevel(logging.WARNING)
return commInst, nil
}
示例5: ListenAndServeGRPC
// ListenAndServeGRPC creates a listener and serves the specified grpc Server
// on it, closing the listener when signalled by the stopper.
func ListenAndServeGRPC(stopper *stop.Stopper, server *grpc.Server,
addr net.Addr) (net.Listener, error) {
ln, err := net.Listen(addr.Network(), addr.String())
if err != nil {
return ln, err
}
stopper.RunWorker(func() {
<-stopper.ShouldDrain()
server.Stop()
})
stopper.RunWorker(func() {
FatalIfUnexpected(server.Serve(ln))
})
return ln, nil
}
示例6: ListenAndServeGRPC
// ListenAndServeGRPC creates a listener and serves server on it, closing
// the listener when signalled by the stopper.
func ListenAndServeGRPC(stopper *stop.Stopper, server *grpc.Server, addr net.Addr, config *tls.Config) (net.Listener, error) {
ln, err := util.Listen(addr, config)
if err != nil {
return nil, err
}
stopper.RunWorker(func() {
if err := server.Serve(ln); err != nil && !util.IsClosedConnection(err) {
log.Fatal(err)
}
})
stopper.RunWorker(func() {
<-stopper.ShouldDrain()
if err := ln.Close(); err != nil {
log.Fatal(err)
}
})
return ln, nil
}
示例7: startRPCServers
func startRPCServers(walletLoader *wallet.Loader) (*grpc.Server, *legacyrpc.Server, error) {
var (
server *grpc.Server
legacyServer *legacyrpc.Server
legacyListen = net.Listen
keyPair tls.Certificate
err error
)
if cfg.DisableServerTLS {
log.Info("Server TLS is disabled. Only legacy RPC may be used")
} else {
keyPair, err = openRPCKeyPair()
if err != nil {
return nil, nil, err
}
// Change the standard net.Listen function to the tls one.
tlsConfig := &tls.Config{
Certificates: []tls.Certificate{keyPair},
MinVersion: tls.VersionTLS12,
NextProtos: []string{"h2"}, // HTTP/2 over TLS
}
legacyListen = func(net string, laddr string) (net.Listener, error) {
return tls.Listen(net, laddr, tlsConfig)
}
if len(cfg.ExperimentalRPCListeners) != 0 {
listeners := makeListeners(cfg.ExperimentalRPCListeners, net.Listen)
if len(listeners) == 0 {
err := errors.New("failed to create listeners for RPC server")
return nil, nil, err
}
creds := credentials.NewServerTLSFromCert(&keyPair)
server = grpc.NewServer(grpc.Creds(creds))
rpcserver.StartWalletLoaderService(server, walletLoader, activeNet)
for _, lis := range listeners {
lis := lis
go func() {
log.Infof("Experimental RPC server listening on %s",
lis.Addr())
err := server.Serve(lis)
log.Tracef("Finished serving expimental RPC: %v",
err)
}()
}
}
}
if cfg.Username == "" || cfg.Password == "" {
log.Info("Legacy RPC server disabled (requires username and password)")
} else if len(cfg.LegacyRPCListeners) != 0 {
listeners := makeListeners(cfg.LegacyRPCListeners, legacyListen)
if len(listeners) == 0 {
err := errors.New("failed to create listeners for legacy RPC server")
return nil, nil, err
}
opts := legacyrpc.Options{
Username: cfg.Username,
Password: cfg.Password,
MaxPOSTClients: cfg.LegacyRPCMaxClients,
MaxWebsocketClients: cfg.LegacyRPCMaxWebsockets,
}
legacyServer = legacyrpc.NewServer(&opts, walletLoader, listeners)
}
// Error when neither the GRPC nor legacy RPC servers can be started.
if server == nil && legacyServer == nil {
return nil, nil, errors.New("no suitable RPC services can be started")
}
return server, legacyServer, nil
}
示例8: serve
func serve(s *grpc.Server, ln net.Listener) {
RegisterWorkerServer(s, &grpcWorker{})
s.Serve(ln)
}
示例9: main
func main() {
configFile := flag.String("config", "", "File path to the configuration file for this service")
flag.Parse()
if *configFile == "" {
flag.Usage()
os.Exit(1)
}
var c config
err := cmd.ReadConfigFile(*configFile, &c)
cmd.FailOnError(err, "Reading JSON config file into config structure")
err = features.Set(c.SA.Features)
cmd.FailOnError(err, "Failed to set feature flags")
stats, logger := cmd.StatsAndLogging(c.Statsd, c.Syslog)
scope := metrics.NewStatsdScope(stats, "SA")
defer logger.AuditPanic()
logger.Info(cmd.VersionString(clientName))
saConf := c.SA
dbURL, err := saConf.DBConfig.URL()
cmd.FailOnError(err, "Couldn't load DB URL")
dbMap, err := sa.NewDbMap(dbURL, saConf.DBConfig.MaxDBConns)
cmd.FailOnError(err, "Couldn't connect to SA database")
go sa.ReportDbConnCount(dbMap, scope)
sai, err := sa.NewSQLStorageAuthority(dbMap, clock.Default(), logger)
cmd.FailOnError(err, "Failed to create SA impl")
var grpcSrv *grpc.Server
if c.SA.GRPC != nil {
var listener net.Listener
grpcSrv, listener, err = bgrpc.NewServer(c.SA.GRPC, scope)
cmd.FailOnError(err, "Unable to setup SA gRPC server")
gw := bgrpc.NewStorageAuthorityServer(sai)
sapb.RegisterStorageAuthorityServer(grpcSrv, gw)
go func() {
err = grpcSrv.Serve(listener)
cmd.FailOnError(err, "SA gRPC service failed")
}()
}
amqpConf := saConf.AMQP
sas, err := rpc.NewAmqpRPCServer(amqpConf, c.SA.MaxConcurrentRPCServerRequests, scope, logger)
cmd.FailOnError(err, "Unable to create SA RPC server")
go cmd.CatchSignals(logger, func() {
sas.Stop()
if grpcSrv != nil {
grpcSrv.GracefulStop()
}
})
err = rpc.NewStorageAuthorityServer(sas, sai)
cmd.FailOnError(err, "Unable to setup SA RPC server")
go cmd.DebugServer(c.SA.DebugAddr)
go cmd.ProfileCmd(scope)
err = sas.Start(amqpConf)
cmd.FailOnError(err, "Unable to run SA RPC server")
}
示例10: main
func main() {
flag.Parse()
ready := make(chan struct{})
go func() {
<-ready
var client helloworld.GreeterClient
if *useGRPC {
opts := []grpc.DialOption{
grpc.WithBlock(),
grpc.WithTimeout(3 * time.Second),
grpc.WithInsecure(),
}
conn, err := grpc.Dial(*addr, opts...)
if err != nil {
log.Fatalf("grpc.Dial: %v", err)
}
client = helloworld.NewGreeterClient(conn)
} else {
t := (http.DefaultTransport.(*http.Transport))
t.TLSClientConfig = &tls.Config{
InsecureSkipVerify: true,
}
if *useHTTP2 {
if err := http2.ConfigureTransport(t); err != nil {
log.Fatal(err)
}
}
}
ctx := context.Background()
for i := 0; i < *numRuns; i++ {
randomBytes := make([]byte, *msgSize)
n, err := rand.Read(randomBytes)
if err != nil {
log.Fatal(err)
}
if n != *msgSize {
log.Fatal("didn't read enough bytes")
}
msg := string(randomBytes)
t1 := time.Now()
var proto string
if *useGRPC {
_, err = client.SayHello(ctx, &helloworld.HelloRequest{Name: msg})
proto = "GRPC"
} else {
var resp *http.Response
resp, err = http.Post("https://"+*addr, "text/plain", bytes.NewReader(randomBytes))
proto = "HTTP"
if resp != nil {
proto = resp.Proto
resp.Body.Close()
}
}
if *verbose {
fmt.Println()
}
fmt.Printf("%v\t%v\t%v\n", time.Now().Sub(t1), *latency, proto)
if err != nil {
log.Fatal(err)
}
}
os.Exit(0)
}()
var server *grpc.Server
if *useGRPC {
server = grpc.NewServer()
helloworld.RegisterGreeterServer(server, greeter{})
}
l, err := net.Listen("tcp", *addr)
if err != nil {
log.Fatal(err)
}
rate := Rate{Latency: *latency}
l = &Listener{l, rate, rate}
close(ready)
if *useGRPC {
log.Fatal(server.Serve(l))
} else {
var config tls.Config
var err error
if *useHTTP2 {
config.NextProtos = []string{"h2"}
}
config.Certificates = make([]tls.Certificate, 1)
config.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
log.Fatal(err)
}
srv := &http.Server{Addr: *addr, TLSConfig: &config, Handler: http.HandlerFunc(validate)}
tlsListener := tls.NewListener(l, &config)
log.Fatal(srv.Serve(tlsListener))
}
}