milvus.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package infra
  2. import (
  3. "context"
  4. "fmt"
  5. "os"
  6. "strings"
  7. "time"
  8. "github.com/milvus-io/milvus-sdk-go/v2/client"
  9. )
  10. // MilvusConfig Milvus 连接配置
  11. type MilvusConfig struct {
  12. Host string
  13. Port string
  14. }
  15. // GetMilvusConfig 从环境变量读取 Milvus 配置
  16. func GetMilvusConfig() *MilvusConfig {
  17. host := os.Getenv("MILVUS_HOST")
  18. if host == "" {
  19. host = "localhost" // 默认值
  20. }
  21. port := os.Getenv("MILVUS_PORT")
  22. if port == "" {
  23. port = "19530" // 默认端口
  24. }
  25. return &MilvusConfig{
  26. Host: host,
  27. Port: port,
  28. }
  29. }
  30. func envTruthy(key string) bool {
  31. v := strings.TrimSpace(strings.ToLower(os.Getenv(key)))
  32. return v == "1" || v == "true" || v == "yes" || v == "on"
  33. }
  34. // IsMilvusDisabled 为 true 时跳过连接 Milvus(不参与 RAG / 向量化,核心 HTTP 仍可启动)。
  35. // 环境变量:MILVUS_DISABLED 或 VECTOR_STORE_DISABLED。
  36. func IsMilvusDisabled() bool {
  37. return envTruthy("MILVUS_DISABLED") || envTruthy("VECTOR_STORE_DISABLED")
  38. }
  39. // IsMilvusRequired 为 true 时,若 Milvus 不可用则启动失败(便于生产环境强依赖向量库时 fail-fast)。
  40. // 环境变量:MILVUS_REQUIRED。
  41. func IsMilvusRequired() bool {
  42. return envTruthy("MILVUS_REQUIRED")
  43. }
  44. // NewMilvusClient 创建 Milvus 客户端连接
  45. func NewMilvusClient() (client.Client, error) {
  46. config := GetMilvusConfig()
  47. // 构建连接地址
  48. address := fmt.Sprintf("%s:%s", config.Host, config.Port)
  49. // 创建客户端
  50. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  51. defer cancel()
  52. milvusClient, err := client.NewClient(
  53. ctx,
  54. client.Config{
  55. Address: address,
  56. Username: os.Getenv("MILVUS_USERNAME"), // 可选
  57. Password: os.Getenv("MILVUS_PASSWORD"), // 可选
  58. },
  59. )
  60. if err != nil {
  61. return nil, fmt.Errorf("连接 Milvus 失败: %w", err)
  62. }
  63. return milvusClient, nil
  64. }
  65. // HealthCheck 检查 Milvus 连接健康状态
  66. func HealthCheck(milvusClient client.Client) error {
  67. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  68. defer cancel()
  69. // 尝试列出集合来验证连接
  70. _, err := milvusClient.ListCollections(ctx)
  71. if err != nil {
  72. return fmt.Errorf("Milvus 健康检查失败: %w", err)
  73. }
  74. return nil
  75. }