linux版本中间件

SqlWrite.cpp 1.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. con.notify_all();
  14. }
  15. void SqlWrite::addSql(const std::string & sql)
  16. {
  17. std::unique_lock<std::mutex>lock(mut);
  18. m_SqlList.emplace_back(sql);
  19. con.notify_all();
  20. }
  21. void SqlWrite::__threadFun()
  22. {
  23. while (!m_Stop)
  24. {
  25. if (__dealSql())
  26. {
  27. std::unique_lock<std::mutex>lock(mut);
  28. con.wait(lock);
  29. }
  30. }
  31. }
  32. bool SqlWrite::__dealSql()
  33. {
  34. std::string sql;
  35. {
  36. std::unique_lock<std::mutex>lock(mut);
  37. if (!m_SqlList.empty())
  38. {
  39. sql = std::move(m_SqlList.front());
  40. m_SqlList.pop_front();
  41. }
  42. }
  43. // 执行sql
  44. if (!sql.empty()){
  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;