Milvus是一个开源的向量数据库,支持高维向量相似度搜索。在使用Milvus时,可以使用连接池来管理连接,提高性能和效率。
在Go语言中,可以使用第三方库如go-redis或者自己实现连接池来管理Milvus的连接。下面给出一个自己实现的简单的Milvus连接池示例:
package milvus
import (
"errors"
"github.com/milvus-io/milvus-sdk-go/milvus"
"sync"
)
type Pool struct {
mu sync.Mutex
connections chan *milvus.MilvusClient
factory func() (*milvus.MilvusClient, error)
size int
closed bool
}
func NewPool(factory func() (*milvus.MilvusClient, error), size int) (*Pool, error) {
if size <= 0 {
return nil, errors.New("invalid pool size")
}
p := &Pool{
connections: make(chan *milvus.MilvusClient, size),
factory: factory,
size: size,
}
for i := 0; i < size; i++ {
conn, err := p.factory()
if err != nil {
p.Close()
return nil, err
}
p.connections <- conn
}
return p, nil
}
func (p *Pool) Get() (*milvus.MilvusClient, error) {
p.mu.Lock()
defer p.mu.Unlock()
if p.closed {
return nil, errors.New("pool is closed")
}
select {
case conn := <-p.connections:
return conn, nil
default:
conn, err := p.factory()
if err != nil {
return nil, err
}
return conn, nil
}
}
func (p *Pool) Put(conn *milvus.MilvusClient) error {
p.mu.Lock()
defer p.mu.Unlock()
if p.closed {
return conn.Close()
}
select {
case p.connections <- conn:
return nil
default:
return conn.Close()
}
}
func (p *Pool) Close() {
p.mu.Lock()
defer p.mu.Unlock()
if p.closed {
return
}
p.closed = true
close(p.connections)
for conn := range p.connections {
conn.Close()
}
}
使用示例:
package main
import (
"fmt"
"github.com/milvus-io/milvus-sdk-go/milvus"
"sync"
)
func main() {
pool, err := milvus.NewPool(func() (*milvus.MilvusClient, error) {
// 连接Milvus服务端
client, err := milvus.NewMilvusClient(milvus.WithAddress("localhost:19530"))
if err != nil {
return nil, err
}
// 登录授权
err = client.Connect(&milvus.ConnectParam{AppID: "test"})
if err != nil {
return nil, err
}
return client, nil
}, 5)
if err != nil {
panic(err)
}
defer pool.Close()
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
wg.Add(1)
go func() {
defer wg.Done()
conn, err := pool.Get()
if err != nil {
panic(err)
}
defer pool.Put(conn)
// 使用连接进行操作
res, err := conn.HasCollection(&milvus.HasCollectionParam{CollectionName: "test"})
if err != nil {
panic(err)
}
fmt.Println(res)
}()
}
wg.Wait()
}