milvus.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package infra
  2. import (
  3. "context"
  4. "fmt"
  5. "os"
  6. "time"
  7. "github.com/milvus-io/milvus-sdk-go/v2/client"
  8. )
  9. // MilvusConfig Milvus 连接配置
  10. type MilvusConfig struct {
  11. Host string
  12. Port string
  13. }
  14. // GetMilvusConfig 从环境变量读取 Milvus 配置
  15. func GetMilvusConfig() *MilvusConfig {
  16. host := os.Getenv("MILVUS_HOST")
  17. if host == "" {
  18. host = "localhost" // 默认值
  19. }
  20. port := os.Getenv("MILVUS_PORT")
  21. if port == "" {
  22. port = "19530" // 默认端口
  23. }
  24. return &MilvusConfig{
  25. Host: host,
  26. Port: port,
  27. }
  28. }
  29. // NewMilvusClient 创建 Milvus 客户端连接
  30. func NewMilvusClient() (client.Client, error) {
  31. config := GetMilvusConfig()
  32. // 构建连接地址
  33. address := fmt.Sprintf("%s:%s", config.Host, config.Port)
  34. // 创建客户端
  35. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  36. defer cancel()
  37. milvusClient, err := client.NewClient(
  38. ctx,
  39. client.Config{
  40. Address: address,
  41. Username: os.Getenv("MILVUS_USERNAME"), // 可选
  42. Password: os.Getenv("MILVUS_PASSWORD"), // 可选
  43. },
  44. )
  45. if err != nil {
  46. return nil, fmt.Errorf("连接 Milvus 失败: %w", err)
  47. }
  48. return milvusClient, nil
  49. }
  50. // HealthCheck 检查 Milvus 连接健康状态
  51. func HealthCheck(milvusClient client.Client) error {
  52. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  53. defer cancel()
  54. // 尝试列出集合来验证连接
  55. _, err := milvusClient.ListCollections(ctx)
  56. if err != nil {
  57. return fmt.Errorf("Milvus 健康检查失败: %w", err)
  58. }
  59. return nil
  60. }