etcd_client.go 1013 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  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. "time"
  8. )
  9. func NewEtcdClient(startup *initutils.Startup) *clientv3.Client {
  10. if startup.RegistryType != "etcd" {
  11. panic("startup registry type not etcd")
  12. }
  13. // etcd client
  14. etcdClient, err := clientv3.New(clientv3.Config{
  15. Endpoints: []string{startup.ConfigSource},
  16. DialTimeout: time.Second * 5,
  17. })
  18. if err != nil {
  19. panic(fmt.Errorf("failed to create etcd client: %w", err))
  20. }
  21. // 检查etcd连接状态
  22. newCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  23. defer cancel()
  24. _, err = etcdClient.Maintenance.Status(newCtx, startup.ConfigSource)
  25. if err != nil {
  26. panic(fmt.Errorf("failed to get etcd status: %w", err))
  27. }
  28. return etcdClient
  29. }
  30. func NewEtcdClientWithCleanup(startup *initutils.Startup) (*clientv3.Client, func()) {
  31. etcdClient := NewEtcdClient(startup)
  32. cleanup := func() {
  33. etcdClient.Close()
  34. }
  35. return etcdClient, cleanup
  36. }