You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

118 lines
2.8 KiB
Go

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

//go:build client
package main
import (
"fmt"
"log"
"sync"
"time"
"github.com/noahlann/nnet/pkg/nnet"
)
func main() {
// 创建连接池配置
poolConfig := &nnet.ClientPoolConfig{
MaxSize: 10, // 最大连接数
MinSize: 2, // 最小连接数(预创建)
ClientConfig: &nnet.ClientConfig{
Addr: "tcp://127.0.0.1:8888",
ConnectTimeout: 5 * time.Second,
ReadTimeout: 5 * time.Second,
WriteTimeout: 5 * time.Second,
},
AcquireTimeout: 5 * time.Second, // 获取连接超时时间
IdleTimeout: 5 * time.Minute, // 空闲连接超时时间
}
// 创建连接池
pool, err := nnet.NewClientPool(poolConfig)
if err != nil {
log.Fatalf("Failed to create connection pool: %v", err)
}
defer pool.Close()
log.Printf("Connection pool created: Size=%d, Available=%d", pool.Size(), pool.Available())
// 等待连接建立
time.Sleep(500 * time.Millisecond)
log.Printf("Connection pool ready: Size=%d, Available=%d", pool.Size(), pool.Available())
// 示例1单个请求
fmt.Println("\n=== 示例1单个请求 ===")
client, err := pool.Acquire()
if err != nil {
log.Fatalf("Failed to acquire connection: %v", err)
}
// 发送请求
request := []byte("echo hello\n")
resp, err := client.Request(request, 5*time.Second)
if err != nil {
log.Printf("Request failed: %v", err)
} else {
fmt.Printf("Response: %s", string(resp))
}
// 释放连接
pool.Release(client)
// 示例2并发请求使用连接池
fmt.Println("\n=== 示例2并发请求 ===")
const numRequests = 20
var wg sync.WaitGroup
wg.Add(numRequests)
for i := 0; i < numRequests; i++ {
go func(id int) {
defer wg.Done()
// 从连接池获取连接
client, err := pool.Acquire()
if err != nil {
log.Printf("Goroutine %d: Failed to acquire connection: %v", id, err)
return
}
// 使用完毕后释放连接
defer pool.Release(client)
// 发送请求
request := []byte(fmt.Sprintf("echo request-%d\n", id))
resp, err := client.Request(request, 5*time.Second)
if err != nil {
log.Printf("Goroutine %d: Request failed: %v", id, err)
return
}
fmt.Printf("Goroutine %d: Response: %s", id, string(resp))
}(i)
}
wg.Wait()
// 示例3获取时间
fmt.Println("\n=== 示例3获取时间 ===")
client, err = pool.Acquire()
if err != nil {
log.Fatalf("Failed to acquire connection: %v", err)
}
defer pool.Release(client)
request = []byte("time\n")
resp, err = client.Request(request, 5*time.Second)
if err != nil {
log.Printf("Request failed: %v", err)
} else {
fmt.Printf("Response: %s", string(resp))
}
// 显示连接池状态
fmt.Printf("\n=== 连接池状态 ===\n")
fmt.Printf("Size: %d\n", pool.Size())
fmt.Printf("Available: %d\n", pool.Available())
fmt.Printf("IsClosed: %v\n", pool.IsClosed())
}