Add an example to test server concurrency.

This commit is contained in:
Chunting Gu
2019-12-06 10:34:36 +08:00
parent 2c75644622
commit 7cb5bca0d0
5 changed files with 46 additions and 11 deletions
+3
View File
@@ -29,6 +29,9 @@ if(UNIX)
set(EXAMPLE_LIBS ${EXAMPLE_LIBS} ${CMAKE_DL_LIBS})
endif()
add_executable(concurrency_test concurrency_test.cc)
target_link_libraries(concurrency_test ${EXAMPLE_LIBS})
add_executable(client_basics client_basics.cc)
target_link_libraries(client_basics ${EXAMPLE_LIBS})
+53
View File
@@ -0,0 +1,53 @@
#include <iostream>
#include <string>
#include <thread>
#include <vector>
#include "webcc/client_session.h"
#include "webcc/logger.h"
int main(int argc, const char* argv[]) {
if (argc < 3) {
std::cerr << "Usage: concurrency_test <workers> <url>" << std::endl;
std::cerr << "E.g.," << std::endl;
std::cerr << " $ concurrency_test 10 https://api.github.com/public/events"
<< std::endl;
std::cerr << " $ concurrency_test 10 http://localhost:8080/" << std::endl;
return 1;
}
WEBCC_LOG_INIT("", webcc::LOG_CONSOLE);
int workers = std::atoi(argv[1]);
std::string url = argv[2];
LOG_USER("Workers: %d", workers);
LOG_USER("URL: %s", url.c_str());
std::vector<std::thread> threads;
for (int i = 0; i < workers; ++i) {
threads.emplace_back([&url]() {
// NOTE: Each thread has its own client session.
webcc::ClientSession session;
session.set_timeout(180);
try {
LOG_USER("Start");
session.Send(webcc::RequestBuilder{}.Get(url)());
LOG_USER("End");
} catch (const webcc::Error& error) {
LOG_ERRO("Error: %s", error.message().c_str());
}
});
}
for (int i = 0; i < workers; ++i) {
threads[i].join();
}
return 0;
}
+26 -3
View File
@@ -4,24 +4,47 @@
class HelloView : public webcc::View {
public:
HelloView(int sleep_seconds) : sleep_seconds_(sleep_seconds) {
}
webcc::ResponsePtr Handle(webcc::RequestPtr request) override {
if (sleep_seconds_ > 0) {
std::this_thread::sleep_for(std::chrono::seconds(sleep_seconds_));
}
if (request->method() == "GET") {
return webcc::ResponseBuilder{}.OK().Body("Hello, World!")();
}
return {};
}
private:
int sleep_seconds_;
};
int main() {
int main(int argc, const char* argv[]) {
WEBCC_LOG_INIT("", webcc::LOG_CONSOLE);
int workers = 1;
int sleep_seconds = 0;
if (argc > 1) {
workers = std::stoi(argv[1]);
if (argc > 2) {
sleep_seconds = std::stoi(argv[2]);
}
}
LOG_USER("Workers: %d", workers);
LOG_USER("Sleep seconds: %d", sleep_seconds);
try {
webcc::Server server(8080);
server.Route("/", std::make_shared<HelloView>());
server.Route("/", std::make_shared<HelloView>(sleep_seconds));
server.Run();
server.Run(workers);
} catch (const std::exception&) {
return 1;