| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263 |
- #include "SqlWrite.h"
- #include <thread>
- #include "Log.h"
- #include "JdbcHelper.h"
- #include <regex>
- SqlWrite::SqlWrite() :m_Stop(false)
- {
- std::thread(std::bind(&SqlWrite::__threadFun, this)).detach();
- }
- SqlWrite::~SqlWrite()
- {
- m_Stop = true;
- con.notify_all();
- }
- void SqlWrite::addSql(const std::string & sql)
- {
- std::unique_lock<std::mutex>lock(mut);
- m_SqlList.emplace_back(sql);
- con.notify_all();
- }
- void SqlWrite::__threadFun()
- {
- while (!m_Stop)
- {
- if (__dealSql())
- {
- std::unique_lock<std::mutex>lock(mut);
- con.wait(lock);
- }
- }
- }
- bool SqlWrite::__dealSql()
- {
- std::string sql;
- {
- std::unique_lock<std::mutex>lock(mut);
- if (!m_SqlList.empty())
- {
- sql = std::move(m_SqlList.front());
- m_SqlList.pop_front();
- }
- }
- // 执行sql
- if (!sql.empty()){
- JdbcHelper::GetInstance()->jdbc_executeUpdate(sql, [](sql::PreparedStatement* stmt) {
- }, [sql](sql::SQLException &e) {
- std::cerr << "exception, SQL: " << sql << std::endl;
- Format fmt("Sql执行失败,错误信息:[%s],Sql[%s]");
- fmt % e.what() % sql;
- LOG_ERROR(fmt.str().c_str());
- });
- }
-
- return m_SqlList.empty();
- }
- SqlWrite SqlWrite::instance;
|