database.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. import mysql.connector
  4. import mysql.connector.pooling
  5. import redis
  6. from mysql.connector import errorcode
  7. import time
  8. import jimit as ji
  9. from initialize import app, logger
  10. __author__ = 'James Iter'
  11. __date__ = '16/6/8'
  12. __contact__ = 'james.iter.cn@gmail.com'
  13. __copyright__ = '(c) 2016 by James Iter.'
  14. class Database(object):
  15. cnxpool = None
  16. r = None
  17. def __init__(self):
  18. pass
  19. @classmethod
  20. def init_conn_mysql(cls):
  21. try:
  22. cls.cnxpool = mysql.connector.pooling.MySQLConnectionPool(
  23. host=app.config["db_host"],
  24. user=app.config["db_user"],
  25. password=app.config["db_password"],
  26. port=app.config["db_port"],
  27. database=app.config["db_name"],
  28. raise_on_warnings=app.config["DEBUG"],
  29. pool_size=app.config["db_pool_size"],
  30. charset=app.config["db_charset"]
  31. )
  32. except mysql.connector.Error as err:
  33. if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
  34. e_msg = u'用户名或密码错误'
  35. elif err.errno == errorcode.ER_BAD_DB_ERROR:
  36. e_msg = u'数据库不存在'
  37. else:
  38. e_msg = err.msg
  39. print(e_msg)
  40. exit(err.errno)
  41. @classmethod
  42. def keepalived_mysql(cls):
  43. def ping(label='', _cnxpool=None):
  44. if _cnxpool is None:
  45. logger.critical(''.join(['cnxpool must not None by ', label]))
  46. return
  47. try:
  48. _cnx = _cnxpool.get_connection()
  49. _cnx.ping(attempts=1, delay=0)
  50. except mysql.connector.errors.InterfaceError as err:
  51. logger.critical(err.msg)
  52. except mysql.connector.Error as err:
  53. logger.error(err)
  54. else:
  55. _cnx.close()
  56. while True:
  57. time.sleep(5)
  58. ping(label='', _cnxpool=cls.cnxpool)
  59. @classmethod
  60. def init_conn_redis(cls):
  61. """
  62. * Added TCP Keep-alive support by passing use the socket_keepalive=True
  63. option. Finer grain control can be achieved using the
  64. socket_keepalive_options option which expects a dictionary with any of
  65. the keys (socket.TCP_KEEPIDLE, socket.TCP_KEEPCNT, socket.TCP_KEEPINTVL)
  66. and integers for values. Thanks Yossi Gottlieb.
  67. TCP_KEEPDILE 设置连接上如果没有数据发送的话,多久后发送keepalive探测分组,单位是秒
  68. TCP_KEEPINTVL 前后两次探测之间的时间间隔,单位是秒
  69. TCP_KEEPCNT 关闭一个非活跃连接之前的最大重试次数
  70. """
  71. import socket
  72. cls.r = redis.StrictRedis(host=app.config.get('redis_host', '127.0.0.1'),
  73. port=app.config.get('redis_port', 6379),
  74. db=app.config.get('redis_dbid', 0), decode_responses=True, socket_timeout=5,
  75. socket_connect_timeout=5, socket_keepalive=True,
  76. socket_keepalive_options={socket.TCP_KEEPIDLE: 2, socket.TCP_KEEPINTVL: 5,
  77. socket.TCP_KEEPCNT: 10},
  78. retry_on_timeout=True)
  79. try:
  80. cls.r.ping()
  81. except redis.exceptions.ResponseError as e:
  82. logger.warn(e.message)
  83. cls.r = redis.StrictRedis(host=app.config.get('redis_host', '127.0.0.1'),
  84. port=app.config.get('redis_port', 6379),
  85. db=app.config.get('redis_dbid', 0), password=app.config.get('redis_password', ''),
  86. decode_responses=True, socket_timeout=5,
  87. socket_connect_timeout=5, socket_keepalive=True,
  88. socket_keepalive_options={socket.TCP_KEEPIDLE: 2, socket.TCP_KEEPINTVL: 5,
  89. socket.TCP_KEEPCNT: 10},
  90. retry_on_timeout=True)
  91. cls.r.client_setname(ji.Common.get_hostname())