1. 程式人生 > >netty學習九:(window7上)python客戶端通過thrift呼叫java服務端

netty學習九:(window7上)python客戶端通過thrift呼叫java服務端

概述

本文簡單介紹使用python編寫客戶端程式碼,通過thrift rpc框架,呼叫java端遠端服務。

在64位window 7上安裝python

python對應的下載連結:python下載

本文使用的版本是

python-2.7.9

下載完後文件名字是

python-2.7.9.amd64.msi

點選直接安裝,一路next即可。

將python配置到path路徑上,配置成功後,啟動CMD,執行

python

正常情況下會出現

Python 2.7.9 (default, Dec 10 2014, 12:28:03) [MSC v.1500
64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>>

下載JetBrains PyCharm

python最好的IDE當屬PyCharm,下載連結為:phcharm下載

下載完的安裝檔名是

pycharm-professional-2017.2.exe

點選安裝,一路next。

安裝完成後,直接建立python工程,工程名字為python_thrift,建立的過程中,PyCharm會自動識別已經安裝到window的python。

建立一個test.py檔案,編寫程式碼

print "hello"

右鍵檔案,選擇【Run ‘test’】,正常情況下會輸出

hello

到此window上的python環境搞定了。

編寫thrift idl檔案

編寫animal.thrift

namespace java thrift.generated
namespace py py.thrift.generated
typedef i16 short
typedef i32 int
typedef i64 long
typedef bool boolean
typedef string String

struct
Animal { 1: optional String username, 2: optional int age, 3: optional boolean married } exception DataException { 1: optional String message, 2: optional String callStack, 3: optional boolean date } service AnimalService { Animal getAnimalByUsername(1: required String name) throws (1: DataException dataException), void saveAnimal(1: required Animal animal) throws (1: DataException dataException) }

animal.thrift完整路徑是

src/main/java/thrift/py/animal.thrift

針對python,需要加入如下一行程式碼

namespace py py.thrift.generated

使用thrift編譯器生成python客戶端類

執行命令

thrift –gen py src/main/java/thrift/py/animal.thrift

注意是gen前面是兩個-,不是一個- .

執行成功後會生成gen-py目錄

gen-py
py
   thrift
     generated
       AnimalService-remote
       AnimalService.py
       constants.py
       ttypes.py

編寫java服務端業務類

package thrift.py;

import org.apache.thrift.TException;

import thrift.py.generated.Animal;
import thrift.py.generated.AnimalService;
import thrift.py.generated.DataException;

/**
 * 業務層服務類 
 *
 */
public class AnimalBizService implements AnimalService.Iface{

    @Override
    public Animal getAnimalByUsername(String name) throws DataException, TException {
        System.out.println("client name:"+name);
        Animal animal = new Animal();
        animal.setUsername(name);
        animal.setAge(34);
        animal.setMarried(true);

        return animal;
    }

    @Override
    public void saveAnimal(Animal animal) throws DataException, TException {
        System.out.println("saveAnimal");
        System.out.println(animal.getUsername());
        System.out.println(animal.getAge());
        System.out.println(animal.isMarried());
    }

}

通常用thrift生成service後,會用一個業務實現類來實現thrift servce介面,完成業務邏輯.

Thrift Server端程式碼

package thrift.py;

import org.apache.thrift.TProcessorFactory;
import org.apache.thrift.protocol.TCompactProtocol;
import org.apache.thrift.server.THsHaServer;
import org.apache.thrift.server.THsHaServer.Args;
import org.apache.thrift.server.TServer;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TNonblockingServerSocket;
import org.apache.thrift.transport.TTransportException;

import thrift.py.generated.AnimalService;

public class ThriftServer {

    public static void main(String[] args) throws TTransportException {
        TNonblockingServerSocket socket = new TNonblockingServerSocket(8899);
        Args arg = new THsHaServer.Args(socket).minWorkerThreads(2).maxWorkerThreads(4);

        AnimalService.Processor<AnimalBizService> processors = new AnimalService.Processor<>(new AnimalBizService());
        arg.protocolFactory(new TCompactProtocol.Factory());
        arg.transportFactory(new TFramedTransport.Factory());
        arg.processorFactory(new TProcessorFactory(processors));

        TServer server = new THsHaServer(arg);
        server.serve();
    }
}

到此java服務端的相關類已經編寫完畢。

下載pytion thrift依賴包

libthrift-0.10.0.jar

同樣編寫python thrift程式碼的時候,也需要一個python依賴包

如何下載這個依賴包呢?可以從thrift原始碼包 取到。

thrift-0.10.0.tar.gz

解壓後,使用CMD命令列切換到

lib\py

目錄下,使用

python setup.py install

安裝依賴包,安裝成功後,可以到python的安裝目錄中的Lib\site-packages找到

thrift-0.10.0-py2.7.egg

到此python thrift依賴包安裝成功。

編寫python thrift 客戶端程式碼

第一步:拷貝thrift生成的python程式碼到python工程中

將之前生成的

gen-py
py
   thrift
     generated
       AnimalService-remote
       AnimalService.py
       constants.py
       ttypes.py

程式碼拷貝到之前建立的python_thrift工程中的根目錄中去.

第二步:編寫python客戶端程式碼

新建立一個python_client.py檔案,程式碼如下

from py.thrift.generated import AnimalService
from py.thrift.generated import ttypes

from thrift import Thrift
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TCompactProtocol

try:
    tSocket = TSocket.TSocket('localhost',8899)
    tSocket.setTimeout(600)

    transport = TTransport.TFramedTransport(tSocket)
    protocol = TCompactProtocol.TCompactProtocol(transport)
    client = AnimalService.Client(protocol)

    transport.open();
    animal = client.getAnimalByUsername("Sam")

    print animal.username
    print animal.age
    print animal.married

    newAnimal = ttypes.Animal()
    newAnimal.username = "Sam2"
    newAnimal.age = 33
    newAnimal.married = False
except Thrift.TException, tx:
    print '%s' % tx.message

執行程式碼

執行ThriftServer類的main方法啟動服務端,執行python_client.py程式碼啟動客戶端,正常情況下會列印如下日誌:

Sam
34
True

csdn code 路徑

這個專案的原始碼放置在csdn code上,歡迎訪問。