注:本文的c++代码是基于ortools开发的
一、运行ortools代码
1. 下载ortools
自己的代码是在下载后的文件or-tools_MacOsX-12.0.1_v9.2.9972/examples/cpp/min_inter.cpp里编写的
2. 终端运行
cd or-tools_MacOsX-12.0.1_v9.2.9972
make run SOURCE=examples/cpp/min_inter.cpp
二、下载配置oatpp环境
1. 获取源码
git clone https://github.com/oatpp/oatpp.git
2. 编译
cd oatpp/
mkdir build && cd build
cmake ..
make
3. 配置
将编译好的文件夹oatpp/src下的oatpp、oatpp-test拷贝到/usr/local/include/oatpp-1.3.0/oatpp下
将编译好的文件oatpp/build/src/liboatpp.a、liboatpp-test.a拷贝到/usr/local/lib/oatpp-1.3.0下
三、编写接口
// 引入oatpp包
#include <oatpp/parser/json/mapping/ObjectMapper.hpp>
#include <oatpp/web/server/HttpConnectionHandler.hpp>
#include <oatpp/network/server/Server.hpp>
#include <oatpp/network/server/SimpleTCPConnectionProvider.hpp>
#include <oatpp/core/macro/codegen.hpp>
using namespace std;
#include OATPP_CODEGEN_BEGIN(DTO)
// 定义返回对象
class MessageDto : public oatpp::data::mapping::type::Object
{
DTO_INIT(MessageDto, Object);
DTO_FIELD(Int32, statusCode);
};
class Handler : public oatpp::web::server::HttpRequestHandler{
private:
std::shared_ptr<oatpp::data::mapping::ObjectMapper> m_objectMapper;
public:
Handler(const std::shared_ptr<oatpp::data::mapping::ObjectMapper> &objectMapper) : m_objectMapper(objectMapper){};
std::shared_ptr<OutgoingResponse> handle(const std::shared_ptr<IncomingRequest> &request) override
{
// 获取参数
auto source = request->getPathVariable("param");
// 运行ortools文件
system("cd or-tools_MacOsX-12.0.1_v9.2.9972 && make run SOURCE=examples/cpp/min_inter.cpp");
// 赋值接口返回结果
auto message = MessageDto::createShared();
message->statusCode = 200;
return ResponseFactory::createResponse(Status::CODE_200, message, m_objectMapper.get());
}
};
void run()
{
auto objectMapper = oatpp::parser::json::mapping::ObjectMapper::createShared();
auto router = oatpp::web::server::HttpRouter::createShared();
// 定义访问路径、请求方式、
router->route("GET", "/hello/{param}", std::make_shared<Handler>(objectMapper));
auto connectionHandler = oatpp::web::server::HttpConnectionHandler::createShared(router);
// 绑定端口号
auto connectionProvider = oatpp::network::server::SimpleTCPConnectionProvider::createShared(10000);
oatpp::network::server::Server server(connectionProvider, connectionHandler);
OATPP_LOGI("MyApp", "Server running on port %s", connectionProvider->getProperty("port").getData());
server.run();
}
int main()
{
oatpp::base::Environment::init();
run();
oatpp::base::Environment::destroy();
return 0;
}
四、编译运行
g++ -o main main.cpp -I/usr/local/include/oatpp-1.3.0/oatpp -L/usr/local/lib/oatpp-1.3.0 -std=c++11 -loatpp -lpthread
./main