Thrift 實現 JAVA,PHP,C#,Python 互相通訊

Thrift介紹   https://www.ibm.com/developerworks/cn/java/j-lo-apachethrift/index.htmlphp

 首先須要下載 Thrift.exe 和Thrift的源碼包,C# Thrift.dll  java Thrift jar包   html

所有放在碼雲上面了 https://gitee.com/bandung/Allthrift.gitjava

 

 

 定義一個thrift文件python

namespace java com.penngo
namespace php com.penngo
namespace py com.penngo
struct User {             定義的是一個結構體,用於同一的放回結果
    1: i64 id,
    2: string name,
    3: string password
}
 
service LoginService{    定義服務,服務先能夠有多個方法,方法返回值爲上面定義的結果User
    User login(1:string name, 2:string psw);
} 

service FaceService{     方法的返回值爲 string類型
    string getFace(1:string name, 2:string psw);
}
 
service RegisterService{
    User createUser(1:string name, 2:string psw);
}

 

生成Python 版本的代碼git

.\thrift-0.9.3.exe -gen  py .\test.thrift   //python
.\thrift-0.9.3.exe -gen  csharp.\test.thrift  //C#
.\thrift-0.9.3.exe -gen  java.\test.thrift    //java
.\thrift-0.9.3.exe -gen  php.\test.thrift   //php

 

 

就生成了這些代碼apache

就簡單舉拿JAVA 作服務端,其餘都是客戶端的例子把,啓動以後監聽了8848端口,多線程模式的,單線程IO阻塞的在git 裏面有api

        try {
            TServerSocket serverTransport = new TServerSocket(8848);
            // 用戶登陸
            LoginService.Processor loginProcessor = new LoginService.Processor(
                    new LoginServiceImpl());
            //人臉識別
            FaceService.Processor faceProcessor=new FaceService.Processor(new FaceServiceImpl());
            // 用戶註冊
            RegisterService.Processor registerProcessor = new RegisterService.Processor(
                    new RegisterServiceImpl());
            
            
             
            TMultiplexedProcessor processor = new TMultiplexedProcessor();
            
            processor.registerProcessor("LoginService", loginProcessor);
            processor.registerProcessor("RegisterService", registerProcessor);
            processor.registerProcessor("FaceService", faceProcessor);
            TServer server = new TThreadPoolServer(new TThreadPoolServer.Args(
                    serverTransport).processor(processor));
            System.out.println("Starting server on port 8848 ...");
            server.serve();
        } catch (TTransportException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }



public static void main(String args[]) {
 
 
Server srv = new Server();
 
 
srv.TMstart();
 
}
 

 

PHP客戶端鏈接多線程

 

<?php
namespace com\penngo;

require_once __DIR__.'/../../php/lib/Thrift/ClassLoader/ThriftClassLoader.php';        //按照本身的目錄來,不能導入錯了
//echo __DIR__.'/../../lib/Thrift/ClassLoader/ThriftClassLoader.php';
use Thrift\ClassLoader\ThriftClassLoader;

$GEN_DIR = realpath(dirname(__FILE__)).'/../../../gen-php';   //按照本身的目錄來,不能導入錯了



$loader = new ThriftClassLoader();
$loader->registerNamespace('Thrift', __DIR__ . '/../../php/lib');  //按照本身的目錄來,不能導入錯了,註冊命名空間
//$loader->registerDefinition('shared', $GEN_DIR);
$loader->registerDefinition('com', $GEN_DIR);
$loader->register();

if (php_sapi_name() == 'cli') {
    ini_set("display_errors", "stderr");
}

use Thrift\Protocol\TBinaryProtocol;
use Thrift\Protocol\TMultiplexedProtocol;
use Thrift\Transport\TSocket;
use Thrift\Transport\THttpClient;
use Thrift\Transport\TBufferedTransport;
use Thrift\Exception\TException;
use com\penngo\RegisterServiceClient;
use com\penngo\LoginServiceClient;

try {

    $socket = new TSocket('127.0.0.1', 8848);
    $socket->setSendTimeout(100000);   //設置超時時間
    $socket->setRecvTimeout(100000);

    $transport = new TBufferedTransport($socket, 1024, 1024);
    $protocol = new TBinaryProtocol($transport);
//    $loginProtocol = new TMultiplexedProtocol($protocol, "LoginService");
    $faceProtocol = new TMultiplexedProtocol($protocol, "FaceService");
    // $registerProtocol = new TMultiplexedProtocol($protocol, "RegisterService");
    $faceClient = new FaceServiceClient($faceProtocol);
    // $registerClient = new RegisterServiceClient($registerProtocol);
    $transport->open();

    $faceinfo = $faceClient->getFace("123","asdasd");

    print_r($faceinfo);

    $transport->close();
} catch (TException $tx) {
    print 'TException: '.$tx->getMessage()."\n";
    print 'TException: '.$tx->getTraceAsString()."\n";
}

 

Python 客戶端app

安裝Python 插件socket

pip install thrift

 

# -*- coding:utf-8 -*-  
import sys
sys.path.append('..')

from thrift.TMultiplexedProcessor import TMultiplexedProcessor
from thrift.protocol.TMultiplexedProtocol import TMultiplexedProtocol
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from thrift.server import TServer
#根據實際的包結構去引入
import FaceService



    

def client():
    transport = TSocket.TSocket(host='localhost', port=8848) 
    transport = TTransport.TBufferedTransport(transport) 
    protocol = TBinaryProtocol.TBinaryProtocol(transport) 
    face_protocol = TMultiplexedProtocol(protocol, "FaceService") #若是服務端使用TMultiplexedProcessor接收處理,客戶端必須用TMultiplexedProtocol而且指定serviceName和服務端的一致 
        
    face_client = FaceService.Client(face_protocol)#msg客戶端 
        
    transport.open() 
    
    print face_client.getFace("123","啊實打實多")
        
    transport.close()


 
if __name__ == '__main__':
    client()
    

 

C# 客戶端

https://gitee.com/bandung/Allthrift/raw/master/gen-csharp/gen-csharp/bin/Debug/Thrift.dll

dll 下載,而後引用

using Thrift.Protocol;
using Thrift.Server;
using Thrift.Transport;

public void TMclient() { TSocket transport = new TSocket("127.0.0.1",8848); TBinaryProtocol protocol = new TBinaryProtocol(transport); TMultiplexedProtocol tprocessor = new TMultiplexedProtocol(protocol, "FaceService"); FaceService.Client faceclient = new FaceService.Client(tprocessor); transport.Open(); String info=faceclient.getFace("PHP","JAVA"); Console.WriteLine(info); transport.Close(); }

 

結束

 

 

 

 

 

 

!!

相關文章
相關標籤/搜索