Documentation
¶
Overview ¶
Package grpc provides gRPC server and client infrastructure with automatic service discovery, health checks, and connection pooling.
This package offers:
- Production-ready gRPC server with graceful shutdown
- Client connection management with load balancing
- Service registration and discovery (Consul integration)
- Health check support (gRPC Health Checking Protocol)
- Reflection API for development tools
- TLS/mTLS support for secure communication
Server Usage ¶
Create and start a gRPC server:
server, err := grpc.NewServer("localhost:50051")
if err != nil {
log.Fatal(err)
}
// Register your services
pb.RegisterYourServiceServer(server.GetServer(), &yourService{})
// Start server
if err := server.Start(); err != nil {
log.Fatal(err)
}
// Graceful shutdown
defer server.Stop()
Client Usage ¶
Create a client connection:
client, err := grpc.NewClient("localhost:50051")
if err != nil {
log.Fatal(err)
}
defer client.Close()
// Use the connection
conn := client.GetConnection()
yourClient := pb.NewYourServiceClient(conn)
Service Discovery ¶
Register service with Consul for automatic discovery:
registry := grpc.NewRegistry(consulClient)
err := registry.Register(ctx, &grpc.ServiceInfo{
ID: "service-1",
Name: "user-service",
Address: "localhost",
Port: 50051,
Tags: []string{"v1", "production"},
})
Discover and connect to services:
services, err := registry.Discover(ctx, "user-service")
if err != nil {
log.Fatal(err)
}
// Connect to first available instance
if len(services) > 0 {
addr := fmt.Sprintf("%s:%d", services[0].Address, services[0].Port)
client, _ := grpc.NewClient(addr)
}
Health Checks ¶
The server automatically registers health check service:
// Set service health status
server.SetServingStatus("user-service", grpc.HealthCheckResponse_SERVING)
// Check from client
healthClient := grpc_health_v1.NewHealthClient(conn)
resp, err := healthClient.Check(ctx, &grpc_health_v1.HealthCheckRequest{
Service: "user-service",
})
TLS Configuration ¶
Enable TLS for secure communication:
server, err := grpc.NewServerWithTLS(
"localhost:50051",
"server.crt",
"server.key",
"ca.crt", // For mTLS
)
Best Practices ¶
- Enable health checks for all production services
- Use service discovery for multi-instance deployments
- Implement proper error handling and retries
- Configure keepalive for long-lived connections
- Use TLS in production environments
- Enable reflection only in development
- Monitor connection pool metrics
- Implement circuit breakers for resilience
Index ¶
- type ClientPool
- type MethodBuilder
- type Server
- type ServiceInfo
- type ServiceMethod
- type ServiceRegistry
- func (r *ServiceRegistry) Close()
- func (r *ServiceRegistry) DiscoverService(ctx context.Context, serviceName string) (string, error)
- func (r *ServiceRegistry) GetConnection(ctx context.Context, serviceName string) (*grpc.ClientConn, error)
- func (r *ServiceRegistry) RegisterService(ctx context.Context, info *ServiceInfo) error
- type SimpleServiceRegistry
- func (r *SimpleServiceRegistry) GetMethod(serviceName, methodName string) (*ServiceMethod, bool)
- func (r *SimpleServiceRegistry) ListMethods(serviceName string) []*ServiceMethod
- func (r *SimpleServiceRegistry) ListServices() []string
- func (r *SimpleServiceRegistry) RegisterMethod(method *ServiceMethod)
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type ClientPool ¶
type ClientPool struct {
// contains filtered or unexported fields
}
ClientPool manages gRPC client connections
func (*ClientPool) CheckHealth ¶
func (p *ClientPool) CheckHealth(ctx context.Context, serviceName string) error
CheckHealth checks service health
func (*ClientPool) GetConnection ¶
func (p *ClientPool) GetConnection(ctx context.Context, serviceName, address string) (*grpc.ClientConn, error)
GetConnection gets or creates a connection to the service
type MethodBuilder ¶
type MethodBuilder struct {
// contains filtered or unexported fields
}
MethodBuilder helps build service method definitions
func NewMethodBuilder ¶
func NewMethodBuilder(serviceName, methodName string) *MethodBuilder
NewMethodBuilder creates a new service method builder
func (*MethodBuilder) Build ¶
func (b *MethodBuilder) Build() *ServiceMethod
Build creates the service method definition
func (*MethodBuilder) WithHandler ¶
func (b *MethodBuilder) WithHandler(handler func(ctx context.Context, req any) (any, error)) *MethodBuilder
WithHandler sets the method handler
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server wraps gRPC server
func NewServer ¶
func NewServer(address string, opts ...grpc.ServerOption) (*Server, error)
NewServer creates a new gRPC server
func (*Server) RegisterService ¶
RegisterService registers a gRPC service
type ServiceInfo ¶
type ServiceInfo struct {
Name string
Address string
Port int
Tags []string
Meta map[string]string
}
ServiceInfo contains gRPC service information
type ServiceMethod ¶
type ServiceMethod struct {
Name string
ServiceName string
Handler func(ctx context.Context, req any) (any, error)
}
ServiceMethod represents a simple service method definition
type ServiceRegistry ¶
type ServiceRegistry struct {
// contains filtered or unexported fields
}
ServiceRegistry handles gRPC service registration and discovery
func NewServiceRegistry ¶
func NewServiceRegistry(consulAddr string) (*ServiceRegistry, error)
NewServiceRegistry creates a new service registry
func (*ServiceRegistry) Close ¶
func (r *ServiceRegistry) Close()
Close closes the registry and all connections
func (*ServiceRegistry) DiscoverService ¶
DiscoverService discovers a service and returns its address
func (*ServiceRegistry) GetConnection ¶
func (r *ServiceRegistry) GetConnection(ctx context.Context, serviceName string) (*grpc.ClientConn, error)
GetConnection gets a gRPC connection to a service
func (*ServiceRegistry) RegisterService ¶
func (r *ServiceRegistry) RegisterService(ctx context.Context, info *ServiceInfo) error
RegisterService registers a gRPC service
type SimpleServiceRegistry ¶
type SimpleServiceRegistry struct {
// contains filtered or unexported fields
}
SimpleServiceRegistry manages simple service methods
func NewSimpleServiceRegistry ¶
func NewSimpleServiceRegistry() *SimpleServiceRegistry
NewSimpleServiceRegistry creates a new simple service registry
func (*SimpleServiceRegistry) GetMethod ¶
func (r *SimpleServiceRegistry) GetMethod(serviceName, methodName string) (*ServiceMethod, bool)
GetMethod gets a service method
func (*SimpleServiceRegistry) ListMethods ¶
func (r *SimpleServiceRegistry) ListMethods(serviceName string) []*ServiceMethod
ListMethods lists all methods for a service
func (*SimpleServiceRegistry) ListServices ¶
func (r *SimpleServiceRegistry) ListServices() []string
ListServices lists all registered services
func (*SimpleServiceRegistry) RegisterMethod ¶
func (r *SimpleServiceRegistry) RegisterMethod(method *ServiceMethod)
RegisterMethod registers a service method