{"id":1521,"date":"2019-02-09T14:23:02","date_gmt":"2019-02-09T14:23:02","guid":{"rendered":"https:\/\/cloudxlab.com\/blog\/?p=1521"},"modified":"2019-04-16T11:14:06","modified_gmt":"2019-04-16T11:14:06","slug":"creating-thrift-service","status":"publish","type":"post","link":"https:\/\/cloudxlab.com\/blog\/creating-thrift-service\/","title":{"rendered":"How to create an Apache Thrift Service &#8211; Tutorial"},"content":{"rendered":"<h2>Overview<\/h2>\n<p>Say you come up with a wonderful idea such as a really great phone service. You would want this phone service to be available to the APIs in various languages. Whether people are using Python, C++, Java or any other programming language, the users should be able to use your service. Also, you would want the users to be able to access globally. In such scenarios, you should create the Thrift Service. Thrift lets you create a generic interface which can be implemented on the server. The clients of this generic interface\u00a0can be automatically generated in all kinds of languages.<\/p>\n<p>Let us get started! Here we are going to create a very simple service that just prints the server time.<\/p>\n<p><!--more--><\/p>\n<h2>Step 0: Install Thrift<\/h2>\n<p>This step is not required if you are using CloudxLab. You can just log in to the web console. In case you want to set up Apache Thrift on your own machine please follow these instructions:\u00a0<a href=\"https:\/\/thrift.apache.org\/docs\/install\/\">https:\/\/thrift.apache.org\/docs\/install\/<\/a><\/p>\n<h2>Step 1: Create the interface definition<\/h2>\n<p>Let us create a file with name Example.thrift with the following code in it:<\/p>\n<pre class=\"lang:default decode:true \">namespace php Example\nservice Example{\n    \/\/ return current time stamp\n    string showCurrentTimestamp()\n     \n    \/\/ wait for 10 seconds, but work asynchronously\n    oneway void asynchronousJob()\n}<\/pre>\n<h2>Step 2: Generate the server and client side code in python<\/h2>\n<pre class=\"lang:default decode:true\">thrift --gen py Example.thrift<\/pre>\n<p>At this point, you will observe a folder with the name &#8220;gen-py&#8221; created in your current directory. Inside gen-py, you would notice that a folder with name &#8220;Example&#8221; has been created with all sorts of code.<\/p>\n<h2>Step3: Create Server<\/h2>\n<p>First, create a directory with the name &#8220;server&#8221; and go into that directory:<\/p>\n<pre class=\"lang:default decode:true \">mkdir\u00a0server\n\ncd server<\/pre>\n<p>Inside this folder create a file with the name\u00a0<em><strong>PythonServer.py <\/strong><\/em>and the following contents<em><strong>:<\/strong><\/em><\/p>\n<pre class=\"lang:default decode:true\">#!\/usr\/bin\/env python\n\n# This server demonstrates Thrift's connection and \"oneway\" asynchronous jobs\n# showCurrentTimestamp : which returns current time stamp from server\n# asynchronousJob() : prints something, waits 10 secs and print another string\n#\n\nport = 9090\n\nimport sys\n# your gen-py dir\nsys.path.append('..\/gen-py')\n\nimport time\n\n# Example files\nfrom Example import *\nfrom Example.ttypes import *\n\n# Thrift files\nfrom thrift.transport import TSocket\nfrom thrift.transport import TTransport\nfrom thrift.protocol import TBinaryProtocol\nfrom thrift.server import TServer\n\n# Server implementation\nclass ExampleHandler:\n    # return current time stamp\n    def showCurrentTimestamp(self):\n        timeStamp = time.time()\n        return str(timeStamp)\n\n    # print something to string, wait 10 secs, than print something again\n    def asynchronousJob(self):\n        print 'Assume that this work takes 10 seconds'\n        time.sleep(10)\n        print 'Job finished, but client didn\\'t wait for 10 seconds'\n\n\n# set handler to our implementation\nhandler = ExampleHandler()\n\nprocessor = Example.Processor(handler)\ntransport = TSocket.TServerSocket(\"0.0.0.0\", port)\ntfactory = TTransport.TBufferedTransportFactory()\npfactory = TBinaryProtocol.TBinaryProtocolFactory()\n\n# set server\nserver = TServer.TThreadedServer(processor, transport, tfactory, pfactory)\n\nprint 'Starting server'\nserver.serve()<\/pre>\n<p>Notice that we are implementing service by the way of the class\u00a0<em><strong>ExampleHandler.<\/strong><\/em><\/p>\n<h2>Step 4: Now start the server:<\/h2>\n<pre class=\"lang:default decode:true \">python PythonServer.py<\/pre>\n<h2>Step 5: Create a client<\/h2>\n<p>Let the server run and open a new terminal.\u00a0In the new terminal follow the instructions from here onwards. Create a folder with the name &#8220;client&#8221;. Inside that folder create a file with name\u00a0<em><strong>PythonClient.py <\/strong><\/em>and the following code:<\/p>\n<pre class=\"lang:default decode:true\">#!\/usr\/bin\/env python\n\n# This client demonstrates Thrift's connection and \"oneway\" asynchronous jobs\n# Client connects to server host:port and calls 2 methods\n# showCurrentTimestamp : which returns current time stamp from server\n# asynchronousJob() : which calls a \"oneway\" method\n#\n\nhost = \"localhost\"\nport = 9090\n\nimport sys\n\n# your gen-py dir\nsys.path.append('..\/gen-py')\n\n# Example files\nfrom Example import *\nfrom Example.ttypes import *\n\n# Thrift files\nfrom thrift import Thrift\nfrom thrift.transport import TSocket\nfrom thrift.transport import TTransport\nfrom thrift.protocol import TBinaryProtocol\n\ntry:\n\n    # Init thrift connection and protocol handlers\n    transport = TSocket.TSocket( host , port)\n    transport = TTransport.TBufferedTransport(transport)\n    protocol = TBinaryProtocol.TBinaryProtocol(transport)\n\n    # Set client to our Example\n    client = Example.Client(protocol)\n\n    # Connect to server\n    transport.open()\n\n    # Run showCurrentTimestamp() method on server\n    currentTime = client.showCurrentTimestamp()\n    print currentTime\n\n    # Assume that you have a job which takes some time\n    # but client sholdn't have to wait for job to finish\n    # ie. Creating 10 thumbnails and putting these files to sepeate folders\n    client.asynchronousJob()\n\n\n    # Close connection\n    transport.close()\n\nexcept Thrift.TException, tx:\n    print 'Something went wrong : %s' % (tx.message)<\/pre>\n<h2>Step 6: Run the client<\/h2>\n<pre class=\"lang:default decode:true\">python PythonClient.py<\/pre>\n<p>It should print the current time such as:<\/p>\n<blockquote><p><em><strong>1549721664.93<\/strong><\/em><\/p><\/blockquote>\n<p>It is an extremely simple example. You can extend it to add more functions and objects.<\/p>\n<p>The code for the whole project is available here:\u00a0<a href=\"https:\/\/github.com\/cloudxlab\/thrift-examples\">https:\/\/github.com\/cloudxlab\/thrift-examples<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Overview Say you come up with a wonderful idea such as a really great phone service. You would want this phone service to be available to the APIs in various languages. Whether people are using Python, C++, Java or any other programming language, the users should be able to use your service. Also, you would &hellip; <a href=\"https:\/\/cloudxlab.com\/blog\/creating-thrift-service\/\" class=\"more-link\">Continue reading<span class=\"screen-reader-text\"> &#8220;How to create an Apache Thrift Service &#8211; Tutorial&#8221;<\/span><\/a><\/p>\n","protected":false},"author":14,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[39,14],"tags":[40],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v16.2 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>How to create an Apache Thrift Service - Tutorial | CloudxLab Blog<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/cloudxlab.com\/blog\/creating-thrift-service\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"How to create an Apache Thrift Service - Tutorial | CloudxLab Blog\" \/>\n<meta property=\"og:description\" content=\"Overview Say you come up with a wonderful idea such as a really great phone service. You would want this phone service to be available to the APIs in various languages. Whether people are using Python, C++, Java or any other programming language, the users should be able to use your service. Also, you would &hellip; Continue reading &quot;How to create an Apache Thrift Service &#8211; Tutorial&quot;\" \/>\n<meta property=\"og:url\" content=\"https:\/\/cloudxlab.com\/blog\/creating-thrift-service\/\" \/>\n<meta property=\"og:site_name\" content=\"CloudxLab Blog\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/cloudxlab\" \/>\n<meta property=\"article:published_time\" content=\"2019-02-09T14:23:02+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2019-04-16T11:14:06+00:00\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@CloudxLab\" \/>\n<meta name=\"twitter:site\" content=\"@CloudxLab\" \/>\n<meta name=\"twitter:label1\" content=\"Est. reading time\">\n\t<meta name=\"twitter:data1\" content=\"4 minutes\">\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebSite\",\"@id\":\"https:\/\/cloudxlab.com\/blog\/#website\",\"url\":\"https:\/\/cloudxlab.com\/blog\/\",\"name\":\"CloudxLab Blog\",\"description\":\"Learn AI, Machine Learning, Deep Learning, Devops &amp; Big Data\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":\"https:\/\/cloudxlab.com\/blog\/?s={search_term_string}\",\"query-input\":\"required name=search_term_string\"}],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/cloudxlab.com\/blog\/creating-thrift-service\/#webpage\",\"url\":\"https:\/\/cloudxlab.com\/blog\/creating-thrift-service\/\",\"name\":\"How to create an Apache Thrift Service - Tutorial | CloudxLab Blog\",\"isPartOf\":{\"@id\":\"https:\/\/cloudxlab.com\/blog\/#website\"},\"datePublished\":\"2019-02-09T14:23:02+00:00\",\"dateModified\":\"2019-04-16T11:14:06+00:00\",\"author\":{\"@id\":\"https:\/\/cloudxlab.com\/blog\/#\/schema\/person\/4835f1b3d5000626cb15e9311d748e09\"},\"breadcrumb\":{\"@id\":\"https:\/\/cloudxlab.com\/blog\/creating-thrift-service\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/cloudxlab.com\/blog\/creating-thrift-service\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/cloudxlab.com\/blog\/creating-thrift-service\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"item\":{\"@type\":\"WebPage\",\"@id\":\"https:\/\/cloudxlab.com\/blog\/\",\"url\":\"https:\/\/cloudxlab.com\/blog\/\",\"name\":\"Home\"}},{\"@type\":\"ListItem\",\"position\":2,\"item\":{\"@id\":\"https:\/\/cloudxlab.com\/blog\/creating-thrift-service\/#webpage\"}}]},{\"@type\":\"Person\",\"@id\":\"https:\/\/cloudxlab.com\/blog\/#\/schema\/person\/4835f1b3d5000626cb15e9311d748e09\",\"name\":\"Sandeep Giri\",\"image\":{\"@type\":\"ImageObject\",\"@id\":\"https:\/\/cloudxlab.com\/blog\/#personlogo\",\"inLanguage\":\"en-US\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/1393214840cf7455bb4cba055cb30468?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/1393214840cf7455bb4cba055cb30468?s=96&d=mm&r=g\",\"caption\":\"Sandeep Giri\"},\"sameAs\":[\"https:\/\/cloudxlab.com\"]}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","_links":{"self":[{"href":"https:\/\/cloudxlab.com\/blog\/wp-json\/wp\/v2\/posts\/1521"}],"collection":[{"href":"https:\/\/cloudxlab.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/cloudxlab.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/cloudxlab.com\/blog\/wp-json\/wp\/v2\/users\/14"}],"replies":[{"embeddable":true,"href":"https:\/\/cloudxlab.com\/blog\/wp-json\/wp\/v2\/comments?post=1521"}],"version-history":[{"count":6,"href":"https:\/\/cloudxlab.com\/blog\/wp-json\/wp\/v2\/posts\/1521\/revisions"}],"predecessor-version":[{"id":2100,"href":"https:\/\/cloudxlab.com\/blog\/wp-json\/wp\/v2\/posts\/1521\/revisions\/2100"}],"wp:attachment":[{"href":"https:\/\/cloudxlab.com\/blog\/wp-json\/wp\/v2\/media?parent=1521"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/cloudxlab.com\/blog\/wp-json\/wp\/v2\/categories?post=1521"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/cloudxlab.com\/blog\/wp-json\/wp\/v2\/tags?post=1521"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}