etcd_client.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package config
  2. import (
  3. "context"
  4. "fmt"
  5. "git.ikuban.com/server/kratos-utils/v2/initutils"
  6. clientv3 "go.etcd.io/etcd/client/v3"
  7. "log"
  8. "time"
  9. )
  10. func NewEtcdClient(startup *initutils.Startup) *clientv3.Client {
  11. if startup.RegistryType != "etcd" {
  12. log.Println("[WARNING] startup registry type not etcd")
  13. return nil
  14. }
  15. // etcd client
  16. etcdClient, err := clientv3.New(clientv3.Config{
  17. Endpoints: []string{startup.ConfigSource},
  18. DialTimeout: time.Second * 5,
  19. })
  20. if err != nil {
  21. panic(fmt.Errorf("failed to create etcd client: %w", err))
  22. }
  23. // 检查etcd连接状态
  24. newCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  25. defer cancel()
  26. _, err = etcdClient.Maintenance.Status(newCtx, startup.ConfigSource)
  27. if err != nil {
  28. panic(fmt.Errorf("failed to get etcd status: %w", err))
  29. }
  30. return etcdClient
  31. }
  32. func NewEtcdClientWithCleanup(startup *initutils.Startup) (*clientv3.Client, func()) {
  33. etcdClient := NewEtcdClient(startup)
  34. if etcdClient == nil {
  35. return nil, func() {}
  36. }
  37. cleanup := func() { etcdClient.Close() }
  38. return etcdClient, cleanup
  39. }