dao.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package dao
  2. import (
  3. "context"
  4. "time"
  5. "go-common/app/job/main/dm/conf"
  6. "go-common/library/cache/memcache"
  7. "go-common/library/cache/redis"
  8. "go-common/library/database/sql"
  9. "go-common/library/log"
  10. )
  11. const (
  12. _subjectSharding = 100
  13. _indexSharding = 1000
  14. )
  15. // Dao dao struct.
  16. type Dao struct {
  17. // redis
  18. redis *redis.Pool
  19. redisExpire int32
  20. // memcache
  21. mc *memcache.Pool
  22. mcExpire int32
  23. // mysql
  24. dmReader *sql.DB
  25. dmWriter *sql.DB
  26. }
  27. // New return dm dao instance.
  28. func New(c *conf.Config) (d *Dao) {
  29. d = &Dao{
  30. // redis
  31. redis: redis.NewPool(c.Redis.Config),
  32. redisExpire: int32(time.Duration(c.Redis.Expire) / time.Second),
  33. // memcache
  34. mc: memcache.NewPool(c.Memcache.Config),
  35. mcExpire: int32(time.Duration(c.Memcache.Expire) / time.Second),
  36. // mysql
  37. dmReader: sql.NewMySQL(c.DB.DMReader),
  38. dmWriter: sql.NewMySQL(c.DB.DMWriter),
  39. }
  40. return
  41. }
  42. func (d *Dao) hitSubject(oid int64) int64 {
  43. return oid % _subjectSharding
  44. }
  45. func (d *Dao) hitIndex(oid int64) int64 {
  46. return oid % _indexSharding
  47. }
  48. // Ping dm dao ping.
  49. func (d *Dao) Ping(c context.Context) (err error) {
  50. if err = d.dmWriter.Ping(c); err != nil {
  51. log.Error("dmWriter.Ping() error(%v)", err)
  52. return
  53. }
  54. if err = d.dmReader.Ping(c); err != nil {
  55. log.Error("dmReader.Ping() error(%v)", err)
  56. return
  57. }
  58. // mc
  59. mconn := d.mc.Get(c)
  60. defer mconn.Close()
  61. if err = mconn.Set(&memcache.Item{Key: "ping", Value: []byte("pong"), Expiration: 0}); err != nil {
  62. log.Error("mc.Set error(%v)", err)
  63. return
  64. }
  65. // dm redis
  66. rconn := d.redis.Get(c)
  67. defer rconn.Close()
  68. if _, err = rconn.Do("SET", "ping", "pong"); err != nil {
  69. rconn.Close()
  70. log.Error("redis.Set error(%v)", err)
  71. }
  72. return
  73. }