Fix api controller instance bug

This commit is contained in:
antao 2018-08-10 22:53:09 +08:00
parent dea4829786
commit 1c47395bb8
3 changed files with 27 additions and 5 deletions

View File

@ -6,7 +6,7 @@
#include <string> #include <string>
using namespace drogon; using namespace drogon;
class A class A:public DrObjectBase
{ {
public: public:
void handle(const HttpRequestPtr& req, void handle(const HttpRequestPtr& req,
@ -26,7 +26,7 @@ public:
callback(*res); callback(*res);
} }
}; };
class B class B:public DrObjectBase
{ {
public: public:
void operator ()(const HttpRequestPtr& req,const std::function<void (HttpResponse &)>&callback,int p1,int p2) void operator ()(const HttpRequestPtr& req,const std::function<void (HttpResponse &)>&callback,int p1,int p2)

View File

@ -17,6 +17,7 @@
#include <drogon/HttpRequest.h> #include <drogon/HttpRequest.h>
#include <drogon/HttpResponse.h> #include <drogon/HttpResponse.h>
#include <drogon/utils/FunctionTraits.h> #include <drogon/utils/FunctionTraits.h>
#include <drogon/DrObject.h>
#include <list> #include <list>
#include <string> #include <string>
#include <sstream> #include <sstream>
@ -52,6 +53,12 @@ namespace drogon{
=0; =0;
virtual size_t paramCount()=0; virtual size_t paramCount()=0;
virtual ~HttpApiBinderBase(){} virtual ~HttpApiBinderBase(){}
protected:
static std::map<std::string,std::shared_ptr<drogon::DrObjectBase>> _objMap;
static std::mutex _objMutex;
}; };
typedef std::shared_ptr<HttpApiBinderBase> HttpApiBinderBasePtr; typedef std::shared_ptr<HttpApiBinderBase> HttpApiBinderBasePtr;
template <typename FUNCTION> template <typename FUNCTION>
@ -136,8 +143,22 @@ namespace drogon{
const HttpRequestPtr& req,std::function<void (HttpResponse &)>callback, const HttpRequestPtr& req,std::function<void (HttpResponse &)>callback,
Values&&... values) Values&&... values)
{ {
static typename traits::class_type obj; static auto className=drogon::DrObjectBase::demangle(typeid(typename traits::class_type).name());
(obj.*_func)(req,callback,std::move(values)...); std::shared_ptr<typename traits::class_type> obj;
{
std::lock_guard<std::mutex> guard(_objMutex);
if(_objMap.find(className)==_objMap.end())
{
obj=std::shared_ptr<typename traits::class_type>(new typename traits::class_type);
_objMap[className]=obj;
}
else
{
obj=std::dynamic_pointer_cast<typename traits::class_type>(_objMap[className]);
}
}
assert(obj);
((*obj).*_func)(req,callback,std::move(values)...);
}; };
template <typename... Values, template <typename... Values,
bool isClassFunction = traits::isClassFunction> bool isClassFunction = traits::isClassFunction>

View File

@ -38,7 +38,8 @@
namespace drogon namespace drogon
{ {
std::map<std::string,std::shared_ptr<drogon::DrObjectBase>> HttpApiBinderBase::_objMap;
std::mutex HttpApiBinderBase::_objMutex;
class HttpAppFrameworkImpl:public HttpAppFramework class HttpAppFrameworkImpl:public HttpAppFramework
{ {
public: public: