linux版本中间件

SqlWrite.cpp 1.6KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. #include "SqlWrite.h"
  2. #include <thread>
  3. #include "Log.h"
  4. #include "JdbcHelper.h"
  5. #include <regex>
  6. SqlWrite::SqlWrite() :m_Stop(false)
  7. {
  8. std::thread(std::bind(&SqlWrite::__threadFun, this)).detach();
  9. }
  10. SqlWrite::~SqlWrite()
  11. {
  12. m_Stop = true;
  13. }
  14. void SqlWrite::addSql(const std::string & sql)
  15. {
  16. std::unique_lock<std::mutex>lock(mut);
  17. m_SqlList.emplace_back(sql);
  18. con.notify_all();
  19. }
  20. void SqlWrite::__threadFun()
  21. {
  22. while (!m_Stop)
  23. {
  24. if (__dealSql())
  25. {
  26. std::unique_lock<std::mutex>lock(mut);
  27. con.wait(lock);
  28. }
  29. }
  30. }
  31. bool SqlWrite::__dealSql()
  32. {
  33. std::string sql;
  34. {
  35. std::unique_lock<std::mutex>lock(mut);
  36. if (!m_SqlList.empty())
  37. {
  38. sql = std::move(m_SqlList.front());
  39. m_SqlList.pop_front();
  40. // 批量执行多个语句
  41. /*volatile int n = 0;
  42. std::list<std::string>::iterator it = m_SqlList.begin();
  43. while (it!= m_SqlList.end())
  44. {
  45. sql = sql + (*it);
  46. sql.append(";");
  47. it = m_SqlList.erase(it);
  48. ++n;
  49. if (n >=20)
  50. break;
  51. }*/
  52. }
  53. }
  54. // 执行sql
  55. if (!sql.empty())
  56. {
  57. /*std::regex reg("'");
  58. sql = std::regex_replace(sql, reg, "\\'");
  59. sql = "call save_sqls('" + sql + "')";*/
  60. /*LOG_DEBUG_S(sql);*/
  61. /*std::string mark = sql.substr(sql.length() - 1, 1);
  62. if (mark == ";")
  63. sql = sql.substr(0, sql.length() - 1);*/
  64. JdbcHelper::GetInstance()->jdbc_executeUpdate(sql, [](sql::PreparedStatement* stmt) {
  65. }, [sql](sql::SQLException &e) {
  66. std::cerr << "exception, SQL: " << sql << std::endl;
  67. Format fmt("Sql执行失败,错误信息:[%s],Sql[%s]");
  68. fmt % e.what() % sql;
  69. LOG_ERROR(fmt.str().c_str());
  70. });
  71. }
  72. return m_SqlList.empty();
  73. }
  74. SqlWrite SqlWrite::instance;