clickhouse.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/ClickHouse/clickhouse-go/v2"
  6. "github.com/ClickHouse/clickhouse-go/v2/lib/driver"
  7. "time"
  8. )
  9. // 创建clickhouse连接
  10. func InitClickHouse(addr []string, size int, database, username, password string) (driver.Conn, error) {
  11. var (
  12. ctx = context.Background()
  13. conn, err = clickhouse.Open(&clickhouse.Options{
  14. //Addr: []string{"cc-2ze9tv451wov14w9e.clickhouse.ads.aliyuncs.com:9000"}, //内网
  15. //Addr: []string{"cc-2ze9tv451wov14w9e.public.clickhouse.ads.aliyuncs.com:9000"}, //外网
  16. Addr: addr,
  17. DialTimeout: 10 * time.Second,
  18. MaxIdleConns: 3,
  19. MaxOpenConns: size,
  20. Auth: clickhouse.Auth{
  21. //Database: "information",
  22. //Username: "biservice",
  23. //Password: "Bi_top95215#",
  24. Database: database,
  25. Username: username,
  26. Password: password,
  27. },
  28. Debugf: func(format string, v ...interface{}) {
  29. fmt.Printf(format, v)
  30. },
  31. })
  32. )
  33. if err != nil {
  34. return nil, err
  35. }
  36. if err := conn.Ping(ctx); err != nil {
  37. if exception, ok := err.(*clickhouse.Exception); ok {
  38. fmt.Printf("Exception [%d] %s \n%s\n", exception.Code, exception.Message, exception.StackTrace)
  39. }
  40. return nil, err
  41. }
  42. return conn, nil
  43. }