dao.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package dao
  2. import (
  3. "context"
  4. "runtime"
  5. "time"
  6. "go-common/app/interface/main/shorturl/conf"
  7. "go-common/library/cache/memcache"
  8. "go-common/library/database/sql"
  9. "go-common/library/log"
  10. )
  11. // Dao struct conf
  12. type Dao struct {
  13. db *sql.DB
  14. memchDB *memcache.Pool
  15. mcExpire int32
  16. cacheCh chan func()
  17. }
  18. // New new dao
  19. func New(c *conf.Config) (d *Dao) {
  20. d = &Dao{
  21. db: sql.NewMySQL(c.Mysql),
  22. memchDB: memcache.NewPool(c.Memcache.Config),
  23. cacheCh: make(chan func(), 1024),
  24. mcExpire: int32(time.Duration(c.Memcache.Expire) / time.Second),
  25. }
  26. for i := 0; i < runtime.NumCPU(); i++ {
  27. go d.cacheproc()
  28. }
  29. return
  30. }
  31. func (d *Dao) cacheproc() {
  32. for {
  33. f, ok := <-d.cacheCh
  34. if !ok {
  35. return
  36. }
  37. f()
  38. }
  39. }
  40. // AddCache add cache chan
  41. func (d *Dao) AddCache(f func()) {
  42. select {
  43. case d.cacheCh <- f:
  44. default:
  45. log.Error("d.cacheCh is full")
  46. }
  47. }
  48. // Close close db.
  49. func (d *Dao) Close() {
  50. if d.db != nil {
  51. d.db.Close()
  52. }
  53. }
  54. // Ping ping dao
  55. func (d *Dao) Ping(c context.Context) (err error) {
  56. if err = d.db.Ping(c); err != nil {
  57. log.Error("d.PingDB error(%v)", err)
  58. }
  59. if err = d.PingMC(c); err != nil {
  60. log.Error("d.PingMC error(%v)", err)
  61. }
  62. return
  63. }
  64. // PingMC ping mc is ok.
  65. func (d *Dao) PingMC(c context.Context) (err error) {
  66. conn := d.memchDB.Get(c)
  67. item := memcache.Item{Key: "ping", Value: []byte{1}, Expiration: d.mcExpire}
  68. if err = conn.Set(&item); err != nil {
  69. log.Error("conn.Set(%s) error(%v)", item.Key, err)
  70. }
  71. conn.Close()
  72. return
  73. }