Thrift - 단순 실 용

간단 한 소개
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 는 언어 간 확장 이 가능 한 서비스 개발 을 위 한 소프트웨어 프레임 워 크 로 소프트웨어 스 택 과 코드 생 성 엔진 을 결합 하여 C + +, 자바, Python... 등 언어 를 구축 하여 틈새 없 이 결합 하고 효율 적 인 서 비 스 를 제공 합 니 다.
설치 하 다.
brew install thrift

역할.
언어 간 호출 로 서로 다른 언어 간 의 장벽 을 깨뜨리다.
크로스 프로젝트 호출, 마이크로 서비스 쪽쪽.
예시
전제 조건
  • thrift 버 전:
  • Go 버 전, Php 버 전, Python 버 전:
  • 설명 하 다.
    이 예 는 python, php, go 세 가지 언어 를 포함한다.(자바 없 음)
    새 HelloThrift. thrift
  • 디 렉 터 리 진입
  • cd /Users/birjemin/Developer/Php/study-php
  • HelloThrift. thrift
  • 작성
    vim HelloThrift.thrift

    내용 은 다음 과 같다.
    namespace php HelloThrift {
      string SayHello(1:string username)
    }

    Php 테스트
  • thrift - phop 라 이브 러 리 불 러 오기
  • composer require apache/thrift
  • php 버 전의 thrift 관련 파일 생 성
  • cd /Users/birjemin/Developer/Php/study-php
    thrift -r --gen php:server HelloThrift.thrift

    이 디 렉 터 리 에 gen-php 라 는 디 렉 터 리 가 생 성 되 었 습 니 다.
  • 작성 Server.php 파일
  • registerDefinition('HelloThrift',$GEN_DIR);
    $loader->register();
    
    class HelloHandler implements \HelloThrift\HelloServiceIf
    {
        public function SayHello($username)
        {
            return "Php-Server: " . $username;
        }
    }
    
    $handler   = new HelloHandler();
    $processor = new \HelloThrift\HelloServiceProcessor($handler);
    $transport = new TBufferedTransport(new TPhpStream(TPhpStream::MODE_R | TPhpStream::MODE_W));
    $protocol  = new TBinaryProtocol($transport,true,true);
    $transport->open();
    $processor->process($protocol,$protocol);
    $transport->close();
  • 작성 Client.php 파일
  • registerDefinition('HelloThrift', $GEN_DIR);
    $loader->register();
    
    if (array_search('--http',$argv)) {
        $socket = new THttpClient('local.study-php.com', 80,'/Server.php');
    } else {
        $host = explode(":", $argv[1]);
        $socket = new TSocket($host[0], $host[1]);
    }
    $transport = new TBufferedTransport($socket,1024,1024);
    $protocol  = new TBinaryProtocol($transport);
    $client    = new \HelloThrift\HelloServiceClient($protocol);
    $transport->open();
    echo $client->SayHello("Php-Client");
    $transport->close();
  • 테스트
  • php Client.php --http

    파 이 썬 테스트
  • thrift - python 3 모듈 불 러 오기 (python 3 만 테스트 하고 python 2 는 테스트 하지 않 음)
  • pip3 install thrift
  • python 3 버 전의 thrift 관련 파일 생 성
  • thrift -r --gen py HelloThrift.thrift

    이 디 렉 터 리 에 gen-py 라 는 디 렉 터 리 가 생 성 되 었 습 니 다.
  • 작성 Server.py 파일
  • #!/usr/bin/python3
    # -*- coding: UTF-8 -*-
    import sys
    sys.path.append('./gen-py')
    
    from HelloThrift import HelloService
    from HelloThrift.ttypes import *
    from thrift.transport import TSocket
    from thrift.transport import TTransport
    from thrift.protocol import TBinaryProtocol
    from thrift.server import TServer
    
    class HelloWorldHandler:
        def __init__(self):
            self.log = {}
    
        def SayHello(self, user_name = ""):
            return "Python-Server: " + user_name
    
    handler = 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()
  • 작성 Client.py 파일
  • #!/usr/bin/python3
    # -*- coding: UTF-8 -*-
    import sys
    sys.path.append('./gen-py')
    
    from HelloThrift import HelloService
    from HelloThrift.ttypes import *
    from HelloThrift.constants import *
    
    from thrift.transport import TSocket
    from thrift.transport import TTransport
    from thrift.protocol import TBinaryProtocol
    
    host = 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()
  • 테스트
  • 새 창 을 열 고 다음 명령 을 실행 합 니 다:
    python3 Server.php

    Go 테스트
  • go 를 불 러 오 는 thrift 모듈
  • go get git.apache.org/thrift.git/lib/go/thrift
  • go 버 전의 thrift 관련 파일 생 성
  • thrift -r --gen go HelloThrift.thrift
  • 파일 생 성 Server.go 파일
  • package main
    
    import (
        "./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()
    }
  • 파일 생 성 Client.go 파일
  • package main
    
    import (
        "./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)
    }
  • 테스트
  • 새 창 을 열 고 다음 명령 을 실행 합 니 다:
    go run Server.go

    종합 테스트
  • 두 개의 창 을 열 어 서버 가 열 릴 수 있 도록 합 니 다
  • go run Server.go # localhost:9092
    python3 Server.py # localhost:9091
  • php 호출 go - server, py - server
  • php Client.php localhost:9091
    php Client.php localhost:9092
  • python 3 호출 go - server, py - server
  • python3 Client.py localhost:9091
    python3 Client.py localhost:9092
  • go 호출 go - server, py - server
  • go run Client.go localhost:9091
    go run Client.go localhost:9092

    비고
  • php 를 테스트 하지 않 은 socket, go, python 3 http, 시간 을 들 여 만 들 수 있 습 니 다
  • 코드 는 순 전 히 조립 에 속 하고 그 중의 원 리 를 깊이 이해 하지 못 했 으 며 후기 에 이론 편 과 패키지 라 이브 러 리 편
  • 을 쓸 계획 이다.
    레 퍼 런 스
  • https://studygolang.com/articles/1120
  • https://www.cnblogs.com/qufo/p/5607653.html
  • https://www.cnblogs.com/lovemdx/archive/2012/11/22/2782180.html
  • https://github.com/yuxel/thrift-examples
  • http://thrift.apache.org/
  • 좋은 웹페이지 즐겨찾기