linux版本中间件

SqlWrite.cpp 1.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #include "SqlWrite.h"
  2. #include <thread>
  3. #include "Log.h"
  4. #include "JdbcHelper.h"
  5. SqlWrite::SqlWrite() :m_Stop(false)
  6. {
  7. std::thread(std::bind(&SqlWrite::__threadFun, this)).detach();
  8. }
  9. SqlWrite::~SqlWrite()
  10. {
  11. m_Stop = true;
  12. }
  13. void SqlWrite::addSql(const std::string & sql)
  14. {
  15. std::unique_lock<std::mutex>lock(mut);
  16. m_SqlList.emplace_back(sql);
  17. con.notify_all();
  18. }
  19. void SqlWrite::__threadFun()
  20. {
  21. while (!m_Stop)
  22. {
  23. if (__dealSql())
  24. {
  25. std::unique_lock<std::mutex>lock(mut);
  26. con.wait(lock);
  27. }
  28. }
  29. }
  30. bool SqlWrite::__dealSql()
  31. {
  32. std::string sql;
  33. {
  34. std::unique_lock<std::mutex>lock(mut);
  35. if (!m_SqlList.empty())
  36. {
  37. sql = std::move(m_SqlList.front());
  38. m_SqlList.pop_front();
  39. }
  40. }
  41. LOG_DEBUG_S(sql);
  42. // 执行sql
  43. if (!sql.empty())
  44. {
  45. JdbcHelper::GetInstance()->jdbc_executeUpdate(sql, [](sql::PreparedStatement* stmt) {
  46. }, [sql](sql::SQLException &e) {
  47. std::cerr << "exception, SQL: " << sql << std::endl;
  48. Format fmt("Sql执行失败,错误信息:[%s],Sql[%s]");
  49. fmt % e.what() % sql;
  50. LOG_ERROR(fmt.str().c_str());
  51. });
  52. }
  53. return m_SqlList.empty();
  54. }
  55. SqlWrite SqlWrite::instance;