dao.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package dao
  2. import (
  3. "context"
  4. "time"
  5. "math/rand"
  6. "go-common/app/service/live/xlottery/conf"
  7. "go-common/library/cache/redis"
  8. xsql "go-common/library/database/sql"
  9. "go-common/library/log"
  10. )
  11. // Dao dao
  12. type Dao struct {
  13. c *conf.Config
  14. //mc *memcache.Pool
  15. redis *redis.Pool
  16. db *xsql.DB
  17. }
  18. // New init mysql db
  19. func New(c *conf.Config) (dao *Dao) {
  20. dao = &Dao{
  21. c: c,
  22. redis: redis.NewPool(c.Redis.Lottery),
  23. db: xsql.NewMySQL(c.Database.Lottery),
  24. }
  25. return
  26. }
  27. // Close close the resource.
  28. func (d *Dao) Close() {
  29. d.redis.Close()
  30. d.db.Close()
  31. }
  32. // Ping dao ping
  33. func (d *Dao) Ping(c context.Context) error {
  34. return d.db.Ping(c)
  35. }
  36. // 通过提供的sql和bind来更新,没有实际业务意义,只是为了少写重复代码
  37. func (d *Dao) execSqlWithBindParams(c context.Context, sql *string, bindParams ...interface{}) (affect int64, err error) {
  38. res, err := d.db.Exec(c, *sql, bindParams...)
  39. if err != nil {
  40. log.Error("db.Exec(%s) error(%v)", *sql, err)
  41. return
  42. }
  43. return res.RowsAffected()
  44. }
  45. func randomString(l int) string {
  46. str := "0123456789abcdefghijklmnopqrstuvwxyz"
  47. bytes := []byte(str)
  48. result := []byte{}
  49. r := rand.New(rand.NewSource(time.Now().UnixNano()))
  50. for i := 0; i < l; i++ {
  51. result = append(result, bytes[r.Intn(len(bytes))])
  52. }
  53. return string(result)
  54. }