thrift-Simple and practical

Source: Internet
Author: User
Tags autoload
This is a creation in Article, where the information may have evolved or changed.

Brief introduction

The Apache Thrift software framework, for scalable cross-language services development, combines a software stack with a code generation engine to build services that work efficiently and seamlessly between C++, Java, Python, PHP, Ruby, Erlang, Perl, Haskell, C#, Cocoa, JavaScript, Node.js, Smalltalk, OCaml and Delphi and other languages.

Apache Thrift is a software framework for extensible cross-language service development combined with a software stack and code generation engine to build C++,java,python ... and other languages, so that they seamlessly combine and efficiently serve.

Installation

brew install thrift

Role

cross-language calls to break the gap between different languages.
Cross-project calls, MicroServices of the DA.

Example

Premise

    • Thrift Version:

    • Go version, PHP version, Python version:

Description

The example contains Python,php,go in three languages. (Java temporarily none)

New Hellothrift.thrift

    • Go to Catalog
cd /Users/birjemin/Developer/Php/study-php
    • Writing Hellothrift.thrift
vim HelloThrift.thrift

The contents are as follows:

namespace php HelloThrift {  string SayHello(1:string username)}

PHP test

    • Loading the thrift-php library
composer require apache/thrift
    • Generate PHP version of thrift related files
cd /Users/birjemin/Developer/Php/study-phpthrift -r --gen php:server HelloThrift.thrift

The directory is then generated with a directory called gen-php .

    • establishing a server.php file
  <?php/** * Created by Phpstorm. * User:birjemin * date:22/02/2018 * time:3:59 PM */namespace hellothrift\ Php;require_once ' vendor/autoload.php '; use Thrift\classloader\thriftclassloader;use Thrift\Protocol\ Tbinaryprotocol;use thrift\transport\tphpstream;use thrift\transport\tbufferedtransport; $GEN _dir = Realpath ( DirName (__file__)). ' /gen-php '; $loader = new Thriftclassloader (); $loader->registerdefinition (' Hellothrift ', $GEN _dir); $loader Register (); class Hellohandler implements \hellothrift\helloserviceif{Public function SayHello ($username) {R Eturn "Php-server:".    $username; }} $handler = new Hellohandler (), $processor = new \hellothrift\helloserviceprocessor ($handler); $transport = new Tbuffere Dtransport (New Tphpstream (Tphpstream::mode_r | TPHPSTREAM::MODE_W); $protocol = new Tbinaryprotocol ($transport, true,true); $transport->open (); $processor Process ($protocol, $protocol); $transport->close ();  
    • establishing a client.php file
  <?php/** * Created by Phpstorm. * User:birjemin * date:22/02/2018 * time:4:00 PM */namespace Hellothrift \php;require_once ' vendor/autoload.php '; use Thrift\classloader\thriftclassloader;use Thrift\Protocol\ Tbinaryprotocol;use Thrift\transport\tsocket;use Thrift\transport\thttpclient;use Thrift\Transport\ Tbufferedtransport;use thrift\exception\texception; $GEN _dir = Realpath (dirname (__file__)). ' /gen-php '; $loader = new Thriftclassloader (); $loader->registerdefinition (' Hellothrift ', $GEN _dir); $loader Register (); if (Array_search ('--http ', $argv)) {$socket = new thttpclient (' local.study-php.com ', '/server.php ');} el    se {$host = explode (":", $argv [1]); $socket = new Tsocket ($host [0], $host [1]);} $transport = new Tbufferedtransport ($socket, 1024,1024), $protocol = new Tbinaryprotocol ($transport); $client = new \hell Othrift\helloserviceclient ($protocol); $transport->open (); Echo $client->sayhello ("php-client"); $transport- >close ();  
    • Test
php Client.php --http

Python test

    • Load the Thrift-python3 module (test python3,python2 is not tested)
pip3 install thrift
    • Generate Python3 version of thrift related files
thrift -r --gen py HelloThrift.thrift

The directory is then generated with a directory called gen-py .

    • Create a Server.py file
#!/usr/bin/python3# -*- coding: UTF-8 -*-import syssys.path.append('./gen-py')from HelloThrift import HelloServicefrom HelloThrift.ttypes import *from thrift.transport import TSocketfrom thrift.transport import TTransportfrom thrift.protocol import TBinaryProtocolfrom thrift.server import TServerclass HelloWorldHandler:    def __init__(self):        self.log = {}    def SayHello(self, user_name = ""):        return "Python-Server: " + user_namehandler = HelloWorldHandler()processor = HelloService.Processor(handler)transport = TSocket.TServerSocket('localhost', 9091)tfactory = TTransport.TBufferedTransportFactory()pfactory = TBinaryProtocol.TBinaryProtocolFactory()server = TServer.TSimpleServer(processor, transport, tfactory, pfactory)server.serve()
    • Create a Client.py file
#!/usr/bin/python3# -*- coding: UTF-8 -*-import syssys.path.append('./gen-py')from HelloThrift import HelloServicefrom HelloThrift.ttypes import *from HelloThrift.constants import *from thrift.transport import TSocketfrom thrift.transport import TTransportfrom thrift.protocol import TBinaryProtocolhost = sys.argv[1].split(':')transport = TSocket.TSocket(host[0], host[1])transport = TTransport.TBufferedTransport(transport)protocol = TBinaryProtocol.TBinaryProtocol(transport)client = HelloService.Client(protocol)transport.open()msg = client.SayHello('Python-Client')print(msg)transport.close()
    • Test

Open a new window and run the following command:

python3 Server.php

Go test

    • Load the Go Thrift module
go get git.apache.org/thrift.git/lib/go/thrift
    • Generate thrift related files for Go version
thrift -r --gen go HelloThrift.thrift
    • Generating Server.go files
package mainimport (    "./gen-go/hellothrift"    "git.apache.org/thrift.git/lib/go/thrift"    "context")const (    NET_WORK_ADDR = "localhost:9092")type HelloServiceTmpl struct {}func (this *HelloServiceTmpl) SayHello(ctx context.Context, str string) (s string, err error) {    return "Go-Server:" + str, nil}func main() {    transportFactory := thrift.NewTTransportFactory()    protocolFactory := thrift.NewTBinaryProtocolFactoryDefault()    transportFactory = thrift.NewTBufferedTransportFactory(8192)    transport, _ := thrift.NewTServerSocket(NET_WORK_ADDR)    handler := &HelloServiceTmpl{}    processor := hellothrift.NewHelloServiceProcessor(handler)    server := thrift.NewTSimpleServer4(processor, transport, transportFactory, protocolFactory)    server.Serve()}
    • Generating Client.go files
package mainimport (    "./gen-go/hellothrift"    "git.apache.org/thrift.git/lib/go/thrift"    "fmt"    "context"    "os")func main() {    var transport thrift.TTransport    args := os.Args    protocolFactory := thrift.NewTBinaryProtocolFactoryDefault()    transport, _ = thrift.NewTSocket(args[1])    transportFactory := thrift.NewTBufferedTransportFactory(8192)    transport, _ = transportFactory.GetTransport(transport)    //defer transport.Close()    transport.Open()    client := hellothrift.NewHelloServiceClientFactory(transport, protocolFactory)    str, _ := client.SayHello(context.Background(), "Go-Client")    fmt.Println(str)}
    • Test

Open a new window and run the following command:

go run Server.go

Comprehensive testing

    • Open two windows to ensure server is turned on
go run Server.go # localhost:9092python3 Server.py # localhost:9091
    • PHP calls Go-server, Py-server
php Client.php localhost:9091php Client.php localhost:9092
    • Python3 calls Go-server, Py-server
python3 Client.py localhost:9091python3 Client.py localhost:9092
    • Go calls Go-server, Py-server
go run Client.go localhost:9091go run Client.go localhost:9092

Note

    1. Without testing PHP's Socket,go, Python3 http, you can take the time to do
    2. The code is purely assembled, without a deep understanding of the principles, and later intends to write a theoretical and encapsulated class library

Reference

    1. https://studygolang.com/articles/1120
    2. https://www.cnblogs.com/qufo/p/5607653.html
    3. https://www.cnblogs.com/lovemdx/archive/2012/11/22/2782180.html
    4. https://github.com/yuxel/ Thrift-examples
    5. http://thrift.apache.org/
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.