一、簡介
首先還是那句話,概念網上已經很多了,我們就不多逼逼了。我來大致介紹一下。
- Thrift是一個RPC框架
- 可以進行異構系統(服務的提供者 和 服務的調用者 不同編程語言開發系統)的RPC調用
- 為什么在當前的系統開發中,會存在著異構系統的RPC?
- 存在異構系統的調用
Python ------> Hbase(Java)
thrift - 遺留系統的整合
- 存在異構系統的調用
- 設計一個異構系統的RPC 解決的核心問題是什么?
肯定:異構系統的RPC 沒有問題 只要雙方 用各自的編程語言實現 網絡編程中(client server)建立網絡連接,進行通信即可。
挑戰:
1. 得需要精通不同編程語言的網絡 IO 線程等相關技術內容 (java go python c delphi…)
2. 通信數據的格式,尤其是二進制的格式,得統一處理(中間的格式)
而thrift就是解決以上問題,作為rpc的框架封裝出來給開發使用。
于是我們可以來看一下他的一些定義和性質特點。
1. 基本概念:是apache組織開源的一個頂級異構系統RPC框架,用于完成異構系統的PRC通信。多種編程語言 Java C++ PHP Phyton Ruby Node.js c# ....2007 FaceBook Thrift 開源。
2. 特點:1. 跨語言支持 2. 開發快速 3. 學習簡單 IDL語言 4. 穩定 3. Thrift的設計思想1. 針對于不同的編程語言提供了一個庫(jar) 作用:網絡通信的代碼 協議(序列化)相關的內容 java libthrift 2. IDL語言 中立語言 用于服務發布3. Thrift命令把IDL語言 自動轉換成 你需要的編程語言。
所以我們現在來總結一下,他就是個rpc框架,并且提供了多語言的異構,我們只需要編寫對應的IDL中間語言文件.thrift文件,然后使用thrift命令,把這個idl中間文件編譯成為目標語言的文件,這樣就生成了對應的類。我們暫時先不說rpc的問題,這個放在我們的實踐篇來說。
二、thrift的使用
1、ThriftRPC安裝
我們需要去參考一下thrift官方文檔,我們看一下其中的安裝操作。
這個安裝操作安裝的就是把IDL轉換成具體編程語言代碼的命令。你可以理解為一個編譯器。
我們可以看到他提供了多種操作系統的安裝方式。
我們以mac為例,那就很簡單了。
brew install thrift
完成安裝即可
thrift -helpthrift --version以上兩個命令都可以用來驗證是否安裝成功。
因為我們是java環境,我們在java環境中開發的,所以我們需要安裝一個庫,針對于不同的編程語言 安裝庫
<dependency><groupId>org.apache.thrift</groupId><artifactId>libthrift</artifactId><version>0.18.0</version>
</dependency>
如果你是python那就pip install thrift ,每種語言都有自己的包管理方式。這里就不多說了。
然后我們還需要在idea中安裝一下thrift的插件支持。
這個插件可以支持我們在idea中進行相應的idl開發。
2、IDL語法
我們上面說了,thrift對于多語言異構的支持是我們編寫一份.thrift文件,這個文件稱之為IDL,然后使用對應的命令來翻譯成目標語言的文件,可見其核心就在這個IDL上,我們來看一下如何編寫IDL的語法。
我們的目的是通過在thrift文件中定義相關的信息,然后通過thrift命令生成各種語言的代碼,這里我們以java為例。
2.1、包路徑:
namespace java com.levi.thrift // 定義java語言的包路徑
namespace go levi.thrift // 定義go語言的包路徑
namespace py levi.thrift // 定義python語言的包路徑
namespace php levi.thrift // 定義php語言的包路徑
namespace csharp levi.thrift // 定義c#語言的包路徑
namespace cpp levi.thrift // 定義c++語言的包路徑
namespace rb levi.thrift // 定義ruby語言的包路徑
namespace perl levi.thrift // 定義perl語言的包路徑
namespace nodejs levi.thrift // 定義nodejs語言的包路徑
namespace lua levi.thrift // 定義lua語言的包路徑
namespace dart levi.thrift // 定義dart語言的包路徑
namespace rust levi.thrift // 定義rust語言的包路徑
namespace swift levi.thrift // 定義swift語言的包路徑
namespace kotlin levi.thrift // 定義kotlin語言的包路徑
namespace typescript levi.thrift // 定義typescript語言的包路徑
2.2、基本類型:
i8: 有符號8位整數類型 在java中就是byte 下面都是java的類型,其余的語言有自己的
i16: 有符號16位整數類型 在java中就是short
i32: 有符號32位整數類型 在java中就是int
i64: 有符號64位整數類型 在java中就是long
double: 64位浮點數類型 在java中就是double
string: 字符串類型 在java中就是String 在所有語言中就是UTF-8編碼的字符串 可以是單引號也可以是雙引號
binary: 二進制類型 在java中就是byte[]
void: 空類型 在java中就是void
2.3、集合類型:
list<T> 有序可重復類型 在java中就是java.util.List<T>
set<T> 無序不可重復類型 在java中就是java.util.Set<T>
map<K,V> 鍵值對類型 在java中就是java.util.Map<K,V>
舉一個map的例子,如果你想生成一個Map<Integer,String>類型的代碼,就要這樣聲明。
map<i32,string> sex = {1:"男",2:"女"}
集合類型是這樣,list<i32> age = [1,2,3,4,5]
2.4、struct 自定義對象
在java中就是實體類,類似于c的結構體:
struct User {1:i32 id,2:string name,3:i32 age}1、舉一個struct的例子,如果你想生成一個User類型的代碼,就要這樣聲明。里面有序號,類型,屬性名稱。2、struct的類不能繼承,成員與成員之間的分割可以是逗號,也可以是分號。3、結構體里面的每一個字段都要進行編號,從1開始。4、結構是變量類型,變量名。5、還有一種類型,叫做optionl,就是可選類型,就是可以為空的類型,就是在序列化的時候是可選的,沒有值就不序列化,有就序列化。默認為每一個成員都加入的關鍵字,可以不寫。我上面就沒寫,其實默認就是。你妹提供默認值,他就不做序列化。6、還有一個關鍵字叫required,就是必須的,就是在序列化的時候是必須的,沒有值就報錯。和optionl相反。你妹提供默認值,他就報錯。舉個例子:其中email就是可選的,name就是必須要有值的。namespace java com.levi.entity
struct User{1: string name ='levi',2: optional i32 age,3: list<i32> ages = [1,2,3,4],4. required i32 hieght
}
2.5、enum 枚舉類型
在java中就是枚舉類:枚舉以逗號分隔,并且不支持嵌套(枚舉內部不能再定義枚舉)
而且枚舉中的整形只能是i32
namespace java com.levi.entity
enum Sex {MALE=1,FEMALE=2}
2.6、異常類型:
exception 異常類型,在java中就是異常類:異常以逗號分隔也可以不分割,啥也不加都行,并且不支持嵌套(異常內部不能再定義異常)而且異常中的整形只能是i32namespace java com.levi.exceptionexception UserException {1: i32 code, 2: string message}
2.7、服務 (Service)
其實就是每種語言中的那些業務類。
服務接口
service UserService{bool login(1:string name,2:string password)void register(1:User user) // 這個User不是實體類,而是我們前面定義的struct, idl語言中的結構體,也就是說你要先定義User這個結構體
}注意:1. 異常:throws關鍵字可以拋出異常之類的,異常列表里面可以有多個異常,這些異常也必須是我們前面定義的idl中的異常service UserService{bool login(1:string name,2:string password) throws (1:UserException e,2:XXXException e)void register(1:User user) // 這個User不是實體類,而是我們前面定義的struct, idl語言中的結構體,也就是說你要先定義User這個結構體 }3. oneway 表示客戶端發起請求后不等待響應返回,立刻往下執行,因為沒有返回值的概念,只能和void 這種操作配合。service UserService{bool login(1:string name,2:string password) throws (1:UserException e,2:XXXException e)oneway void register(1:User user) // 這個User不是實體類,而是我們前面定義的struct, idl語言中的結構體,也就是說你要先定義User這個結構體 }4. 繼承,和struct不同,這里可以繼承service BaseService{void m1(1:string name)}service UserService extends BaseService{}
2.8、include(模塊化)
作用:進行IDL模塊化編程
可以在一個thrift文件中,以include命令引入其他的thrift文件作為使用,最終生成的文件里面會引用,并且去掉前綴啥的。他的含義就是對應著你在一個類里面引用其他的包的類或者實體,這樣的一個效果。
levi1.thriftstruct User{1:string name}
levi2.thrift include "levi1.thrift"service UserService{void register(1:levi1.User user)}
2.9、注釋
# 單行注釋
// 單行注釋
/** 多行注釋*/
3、實際操作IDL
先在pom文件中引入一下jar包依賴。
<dependency><groupId>org.apache.thrift</groupId><artifactId>libthrift</artifactId><version>0.22.0</version></dependency>
Thrift把IDL生成對應代碼的命令:
thrift --gen java xx.thrift
thrift --gen py xx.thrift
以上是兩種翻譯為java和py的命令,其余的語言可以查看文檔。thrift --helplevi@192 ~ % thrift --help
Usage: thrift [options] file
Options:-version Print the compiler version-o dir Set the output directory for gen-* packages(default: current directory)-out dir Set the ouput location for generated files.(no gen-* folder will be created)-I dir Add a directory to the list of directoriessearched for include directives-nowarn Suppress all compiler warnings (BAD!)-strict Strict compiler warnings on-v[erbose] Verbose mode-r[ecurse] Also generate included files-debug Parse debug trace to stdout--allow-neg-keys Allow negative field keys (Used to preserve protocolcompatibility with older .thrift files)--allow-64bit-consts Do not print warnings about using 64-bit constants--gen STR Generate code with a dynamically-registered generator.STR has the form language[:key1=val1[,key2[,key3=val3]]].Keys and values are options passed to the generator.Many options will not require values.Options related to audit operation--audit OldFile Old Thrift file to be audited with 'file'-Iold dir Add a directory to the list of directoriessearched for include directives for old thrift file-Inew dir Add a directory to the list of directoriessearched for include directives for new thrift fileAvailable generators (and options):c_glib (C, using GLib):cl (Common Lisp):no_asd: Do not define ASDF systems for each generated Thrift program.sys_pref= The prefix to give ASDF system names. Default: thrift-gen-cpp (C++):cob_style: Generate "Continuation OBject"-style classes.no_client_completion:Omit calls to completion__() in CobClient class.no_default_operators:Omits generation of default operators ==, != and <templates: Generate templatized reader/writer methods.pure_enums: Generate pure enums instead of wrapper classes.include_prefix: Use full include paths in generated files.moveable_types: Generate move constructors and assignment operators.no_ostream_operators:Omit generation of ostream definitions.no_skeleton: Omits generation of skeleton.d (D):dart (Dart):library_name: Optional override for library name.library_prefix: Generate code that can be used within an existing library.Use a dot-separated string, e.g. "my_parent_lib.src.gen"pubspec_lib: Optional override for thrift lib dependency in pubspec.yaml,e.g. "thrift: 0.x.x". Use a pipe delimiter to separate lines,e.g. "thrift:| git:| url: git@foo.com"delphi (Delphi):register_types: Enable TypeRegistry, allows for creation of struct, unionand container instances by interface or TypeInfo()constprefix: Name TConstants classes after IDL to reduce ambiguitiesevents: Enable and use processing events in the generated code.xmldoc: Enable XMLDoc comments for Help Insight etc.async: Generate IAsync interface to use Parallel Programming Library (XE7+ only).com_types: Use COM-compatible data types (e.g. WideString).old_names: Compatibility: generate "reserved" identifiers with '_' postfix instead of '&' prefix.rtti: Activate {$TYPEINFO} and {$RTTI} at the generated API interfaces.erl (Erlang):legacynames: Output files retain naming conventions of Thrift 0.9.1 and earlier.delimiter= Delimiter between namespace prefix and record name. Default is '.'.app_prefix= Application prefix for generated Erlang files.maps: Generate maps instead of dicts.go (Go):package_prefix= Package prefix for generated files.thrift_import= Override thrift package import path (default:github.com/apache/thrift/lib/go/thrift)package= Package name (default: inferred from thrift file name)ignore_initialismsDisable automatic spelling correction of initialisms (e.g. "URL")read_write_privateMake read/write methods private, default is public Read/Writeskip_remoteSkip the generating of -remote folders for the client binaries for servicesgv (Graphviz):exceptions: Whether to draw arrows from functions to exception.haxe (Haxe):rtti Enable @:rtti for generated classes and interfacesbuildmacro=my.macros.Class.method(args)Add @:build macro calls to generated classes and interfaceshtml (HTML):standalone: Self-contained mode, includes all CSS in the HTML files.Generates no style.css file, but HTML files will be larger.noescape: Do not escape html in doc text.java (Java):beans: Members will be private, and setter methods will return void.private_members: Members will be private, but setter methods will return 'this' like usual.private-members: Same as 'private_members' (deprecated).nocamel: Do not use CamelCase field accessors with beans.fullcamel: Convert underscored_accessor_or_service_names to camelCase.android: Generated structures are Parcelable.android_legacy: Do not use java.io.IOException(throwable) (available for Android 2.3 and above).option_type=[thrift|jdk8]:thrift: wrap optional fields in thrift Option type.jdk8: Wrap optional fields in JDK8+ Option type.If the Option type is not specified, 'thrift' is used.rethrow_unhandled_exceptions:Enable rethrow of unhandled exceptions and let them propagate further. (Default behavior is to catch and log it.)java5: Generate Java 1.5 compliant code (includes android_legacy flag).future_iface: Generate CompletableFuture based iface based on async client.reuse_objects: Data objects will not be allocated, but existing instances will be used (read and write).reuse-objects: Same as 'reuse_objects' (deprecated).sorted_containers:Use TreeSet/TreeMap instead of HashSet/HashMap as a implementation of set/map.generated_annotations=[undated|suppress]:undated: suppress the date at @Generated annotationssuppress: suppress @Generated annotations entirelyunsafe_binaries: Do not copy ByteBuffers in constructors, getters, and setters.jakarta_annotations: generate jakarta annotations (javax by default)annotations_as_metadata:Include Thrift field annotations as metadata in the generated code.javame (Java ME):js (Javascript):jquery: Generate jQuery compatible code.node: Generate node.js compatible code.ts: Generate TypeScript definition files.with_ns: Create global namespace objects when using node.jses6: Create ES6 code with Promisesthrift_package_output_directory=<path>:Generate episode file and use the <path> as prefiximports=<paths_to_modules>:':' separated list of paths of modules that has episode files in their rootjson (JSON):merge: Generate output with included files mergedkotlin (Kotlin):lua (Lua):omit_requires: Suppress generation of require 'somefile'.markdown (Markdown):suffix: Create files/links with/out 'md|html' default Nonenoescape: Do not escape with html-entities in doc text.netstd (C#):wcf: Adds bindings for WCF to generated classes.serial: Add serialization support to generated classes.union: Use new union typing, which includes a static read function for union types.pascal: Generate Pascal Case property names according to Microsoft naming convention.net6: Enable features that require net6 and C# 8 or higher.net8: Enable features that require net8 and C# 12 or higher.no_deepcopy: Suppress generation of DeepCopy() method.async_postfix: Append "Async" to all service methods (maintains compatibility with existing code).ocaml (OCaml):perl (Perl):php (PHP):inlined: Generate PHP inlined filesserver: Generate PHP server stubsoop: Generate PHP with object oriented subclassesclassmap: Generate old-style PHP files (use classmap autoloading)rest: Generate PHP REST processorsnsglobal=NAME: Set global namespacevalidate: Generate PHP validator methodsjson: Generate JsonSerializable classes (requires PHP >= 5.4)getters_setters: Generate Getters and Setters for struct variablespy (Python):zope.interface: Generate code for use with zope.interface.twisted: Generate Twisted-friendly RPC services.tornado: Generate code for use with Tornado.no_utf8strings: Do not Encode/decode strings using utf8 in the generated code. Basically no effect for Python 3.coding=CODING: Add file encoding declare in generated file.slots: Generate code using slots for instance members.dynamic: Generate dynamic code, less code generated but slower.dynbase=CLS Derive generated classes from class CLS instead of TBase.dynfrozen=CLS Derive generated immutable classes from class CLS instead of TFrozenBase.dynexc=CLS Derive generated exceptions from CLS instead of TExceptionBase.dynfrozenexc=CLS Derive generated immutable exceptions from CLS instead of TFrozenExceptionBase.dynimport='from foo.bar import CLS'Add an import line to generated code to find the dynbase class.package_prefix='top.package.'Package prefix for generated files.old_style: Deprecated. Generate old-style classes.enum: Generates Python's IntEnum, connects thrift to python enums. Python 3.4 and higher.type_hints: Generate type hints and type checks in write method. Requires the enum option.rb (Ruby):rubygems: Add a "require 'rubygems'" line to the top of each generated file.namespaced: Generate files in idiomatic namespaced directories.rs (Rust):st (Smalltalk):swift (Swift 3.0):log_unexpected: Log every time an unexpected field ID or type is encountered.debug_descriptions:Allow use of debugDescription so the app can add description via a cateogory/extensionasync_clients: Generate clients which invoke asynchronously via block syntax.namespaced: Generate source in Module scoped output directories for Swift Namespacing.cocoa: Generate Swift 2.x code compatible with the Thrift/Cocoa librarypromise_kit: Generate clients which invoke asynchronously via promises (only use with cocoa flag)safe_enums: Generate enum types with an unknown case to handle unspecified values rather than throw a serialization errorxml (XML):merge: Generate output with included files mergedno_default_ns: Omit default xmlns and add idl: prefix to all elementsno_namespaces: Do not add namespace definitions to the XML modelxsd (XSD):
我們這里來試試翻譯java。thrift -r --gen java xx.thrift -r表示include也一起生成,其他模塊的也引入進來。
我們首先來編一個idl文件test1.thrift
namespace java com.levi.entity
struct User{1: string name ='levi',2: optional i32 age,3: list<i32> ages = [1,2,3,4],4: required i32 hieght
}exception UserException {# 異常編碼1: i32 code,# 異常信息2: string message
}
然后我們再來編寫一個idl文件test2.thrift
并且我們引入了這個test1里面的User。
include "test1.thrift"service UserService{void add(1:test1.User user)
}
我們進入這個目錄:
然后執行thrift -r --gen java xx.thrift 來生成對應的類,但是還有一個問題,我們的test2里面引用了test1,所以我們應該先生成test1然后test2,要是引用關系復雜那不就煩死了,于是thrift提供了一個命令-r參數。
他可以遞歸的翻譯,所有包括include的一起生成,比如我們test2中引用了test1,那么我們只需要-r test2就可以了,test1可以順帶一起生成,于是我們的命令就變成了。
thrift -r --gen java test2.thrift
執行之后就會在同級目錄下生成對應的thrift的java類。
此時注意,他不是我們的java源代碼,我們需要把他復制到我們的src類包里面才能用。復制完了之后就可以把那些thrift的產物刪了。
或者你也可以使用-o參數來指定你要輸出的路徑。
ok我們來看下我們的類。
我們發現@javax.annotation.Generated這個注解報錯,這是因為我用的是jdk11,jdk11及其以上移除了該包,可以使用jar替代,我們重新引入一下即可。
<dependency><groupId>javax.annotation</groupId><artifactId>javax.annotation-api</artifactId><version>1.3.2</version>
</dependency>
此時我的pom如下。
<properties><thrift.version>0.22.0</thrift.version><maven.compiler.source>11</maven.compiler.source><maven.compiler.target>11</maven.compiler.target><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties><dependencies><dependency><groupId>org.apache.thrift</groupId><artifactId>libthrift</artifactId><version>${thrift.version}</version></dependency><dependency><groupId>javax.annotation</groupId><artifactId>javax.annotation-api</artifactId><version>1.3.2</version></dependency>
</dependencies>
ok,此時我們就生成了thrift rpc的一些必備前置物料了,后面我們將使用這個rpc框架進行通信,而他封裝的那些語言異構也好,還是傳輸協議上的極致的壓縮消息都是非常優秀的,這個框架在dubbo中大放異彩。
4、踩坑
register是thrift的關鍵字,不要用這個做命名方法或者參數啥的。