This package provides a connection pool for gRPC clients in Go, allowing efficient management and reuse of gRPC connections.
- Configurable minimum and maximum number of connections
- Automatic connection creation and cleanup
- Idle timeout for unused connections
- Concurrent-safe connection management
- Simple API for getting and releasing connections
To install the gRPC connection pool package, use the following command:
go get github.com/t34-dev/go-grpc-pool
Ensure that you have Go modules enabled in your project.
Here's a basic example of how to use the gRPC connection pool in your project:
package main
import (
"context"
"log"
"time"
"github.com/t34-dev/go-grpc-pool"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
func main() {
// Define a factory function to create gRPC connections
factory := func() (*grpc.ClientConn, error) {
return grpc.Dial("localhost:50053",
grpc.WithTransportCredentials(insecure.NewCredentials()),
grpc.WithBlock(),
grpc.WithTimeout(5*time.Second))
}
// Create a new connection pool
pool, err := grpcpool.NewPool(factory, grpcpool.PoolOptions{
MinConn: 2,
MaxConn: 10,
IdleTimeout: 5 * time.Minute,
WaitGetConn: 20 * time.Second,
})
if err != nil {
log.Fatalf("Failed to create pool: %v", err)
}
defer pool.Close()
// Get a connection from the pool
conn, err := pool.Get()
if err != nil {
log.Fatalf("Failed to get connection: %v", err)
}
defer conn.Free() // Return the connection to the pool when done
// Use the connection to make gRPC calls
client := yourpackage.NewYourServiceClient(conn.GetConn())
resp, err := client.YourMethod(context.Background(), &yourpackage.YourRequest{})
if err != nil {
log.Fatalf("Error calling YourMethod: %v", err)
}
log.Printf("Response: %v", resp)
}
The PoolOptions
struct allows you to configure the connection pool:
MinConn
: Minimum number of connections to maintain in the poolMaxConn
: Maximum number of connections allowed in the poolIdleTimeout
: Duration after which idle connections are closedWaitGetConn
: Maximum duration to wait for an available connectionLogger
: Optional logger interface for debugging
To run the tests for this package, use the following command:
make test
To generate protobuf files (if needed):
make protoc
To run the example server:
make server
To run the example client:
make client
This project is licensed under the ISC License. See the LICENSE file for details.
Contributions are welcome! Please feel free to submit a Pull Request.
Developed with ❤️ by T34