Apache Thrift is a framework for scalable cross-language services development. Compared to SOAP-based and JSON-based web services, Thrift uses its own interface definition language and binary format in communication.
Here are the steps to setup thrift and use it to build a hello world web service.
1. Get Thrift source code.
git clone https://git-wip-us.apache.org/repos/asf/thrift.git thrift
cd thrift
2. Install required tools and libraries.
sudo apt-get install libboost-dev libboost-test-dev libboost-program-options-dev libevent-dev automake libtool flex bison pkg-config g++ libssl-dev
3. Build and install Thrift
./bootstrap.sh
./configure
make
make install
4. Define a simple service interface
# helloworld.thrift
service Foo {
string bar();
}
5. Generate boilerplate codes
thrift --gen cpp helloworld.thrift
thrift --gen py helloworld.thrift
6. Implement the server in C++.
In gen-cpp folder, edit the file Foo_server.skeleton.cpp
, which is an auto-generated skeleton file for server implementation.
class FooHandler : virtual public FooIf {
public:
void bar(std::string& _return) {
_return = "Hello World";
}
};
In gen-cpp
folder, create a CMakeLists.txt
file with the following content.
cmake_minimum_required (VERSION 2.6)
project (server)
link_libraries(libthrift.so)
aux_source_directory(. sources)
add_executable(server ${sources})
Then run the following commands.
cmake. && make
7. Implement the client in Python.
In gen-py
folder, create a client.py
with the following content.
import sys
from thrift.transport import TTransport
from thrift.transport import TSocket
from thrift.protocol import TBinaryProtocol
from helloworld import Foo
from helloworld.ttypes import *
socket = TSocket.TSocket('localhost', 9090)
transport = TTransport.TBufferedTransport(socket)
protocol = TBinaryProtocol.TBinaryProtocol(transport)
client = Foo.Client(protocol)
transport.open()
print(client.bar())
transport.close()
9. Start server.
cd gen-cpp
server &
10. Start client.
cd gen-py
python client.py
And the text Hello World
should be printed out.
No comments:
Post a Comment