thrift IDL 基本类型和实践(四)service(服务)、namespace、保留关键字

2,980 阅读2分钟

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

简介

Thrift 通过 IDL(Interface Definition Language)定义通用的服务接口,通过 Thrift 提供的编译器,将 IDL 编译为不同语言的代码,通过这个方式实现跨语言的功能。

我写的这个系列的文章,参考了两篇比较好的文章,从实践的角度看下 Thrift IDL 的编写

文章系列

service(服务)

在语义上等同于接口定义

struct GetAnimalInfoResponse {
    1: required i32 code;  // 应该是 enum 类型的,简化例子省略
    2: required string message;
}
struct GetAnimalInfoRequest {
    1: required i32 id;
}
service AnimalService {
 GetAnimalInfoResponse GetAnimalInfo(1: GetAnimalInfoRequest request);
 string GetAnimalName(1: i32 id);
 void SaveAnimal()
}

参考 GetAnimalInfo,一般实际情况,我们的参数和返回值会定义为 struct,因为一般都是结构化的数据,如果没有返回值,可以写 void

namespace(命名空间)

Thrift 中的命名空间类似于 C++ 中的 namespace 和 java 中的 package,它们提供了一种组织(隔离)代码的简便方式。

namespace 中文意思是命名空间或者叫名字空间,传统的 C++ 只有一个全局的 namespace,但是由于现在的程序的规模越来越大,程序的分工越来越细,全局作用域变得越来越拥挤,每个人都可能使用相同的名字来实现不同的库,于是程序员在合并程序的时候就会可能出现名字的冲突。namespace 引入了复杂性,解决了这个问题。namespace 允许像类,对象,函数聚集在一个名字下。本质上讲 namespace 是对全局作用域的细分。

引用自:blog.csdn.net/jameshater/…

于是在实际应用中,我们通过给 thrift 文件设定不同的命名空间来防止冲突

// example.thrift
namespace py home.example
namespace go home.example

保留关键字

来自:thrift.apache.org/docs/idl.ht…

"BEGIN", "END", "__CLASS__", "__DIR__", "__FILE__", "__FUNCTION__",
"__LINE__", "__METHOD__", "__NAMESPACE__", "abstract", "alias", "and", "args", "as",
"assert", "begin", "break", "case", "catch", "class", "clone", "continue", "declare",
"def", "default", "del", "delete", "do", "dynamic", "elif", "else", "elseif", "elsif",
"end", "enddeclare", "endfor", "endforeach", "endif", "endswitch", "endwhile", "ensure",
"except", "exec", "finally", "float", "for", "foreach", "from", "function", "global",
"goto", "if", "implements", "import", "in", "inline", "instanceof", "interface", "is",
"lambda", "module", "native", "new", "next", "nil", "not", "or", "package", "pass",
"public", "print", "private", "protected", "raise", "redo", "rescue", "retry", "register",
"return", "self", "sizeof", "static", "super", "switch", "synchronized", "then", "this",
"throw", "transient", "try", "undef", "unless", "unsigned", "until", "use", "var",
"virtual", "volatile", "when", "while", "with", "xor", "yield" 

以上是 thrift IDL 基本类型和实践的全部内容,欢迎点赞和评论,谢谢~