Thrift Getting Started Guide

Source: Internet
Author: User
Tags bool constant function definition inheritance stub in python

I. SUMMARY OF CONTENTS
Thrift is a cross-language service deployment framework that was originally developed by Facebook in 2007 and entered the Apache Open source project in 2008. Thrift defines RPC interfaces and data types through an intermediate language (IDL, Interface Definition Language), and then generates code in different languages via a compiler (currently supports C++,java, Python, PHP, Ruby, Erlang, Perl, Haskell, C #, Cocoa, Smalltalk, and OCaml), and the generated code is responsible for the implementation of the RPC protocol layer and the Transport layer.
The previous article focused on the introduction of the thrift Framework. The main object of this article is the thrift file, and how to write the client and server.

Second, thrift grammar
1. Thrift Type

The thrift type System includes predefined basic types, user-defined structures, container types, exceptions, and service definitions
(1) Basic type

<span style= "FONT-SIZE:14PX;" >bool: Boolean type (True or value), accounting for a byte byte 
: Signed byte 
i16:16 bit signed integer i32:32 bit signed integer 
i64:64 bit 
signed integral type double:64 bit floating point 
string: Unknown encoded or binary string </span>

Note that thrift does not support unsigned integers because there are no unsigned integers (such as Java) in many target languages.
(2) Container type
The thrift container is closely related to the type, which corresponds to the type of container provided by the current popular programming language and is represented in the Java generic style. The thrift provides 3 types of containers:
LIST&LT;T1&GT: An ordered table of elements of a series of T1 types that can be duplicated. Equivalent to list in Java
SET&LT;T1&GT: An unordered table of elements of a series of T1 types, elements unique. Equivalent to set in Java
Map<t1,t2>:key/value pair (the type of key is T1 and key is unique, and the value type is t2). Equivalent to a map in Java
The type of element in a container can be any legitimate thrift type (including structs and exceptions) except for service surprises.
(3) Structure and anomalies
The thrift struct is conceptually the same as the C-language struct type-a way to aggregate (encapsulate) related attributes together. In object-oriented languages, the thrift struct is transformed into a class. Structs Use the struct keyword declaration.
Exceptions are syntactically and functionally similar to structs, except that exceptions are declared using the keyword exception instead of the struct keyword. But it is semantically different from the struct-when you define an RPC service, the developer may need to declare a remote method to throw an exception.
The declarations of structs and exceptions are described in the next section.
(4) Service
The definition method of a service is syntactically equivalent to defining an interface in an object-oriented language. The thrift compiler produces client and server piles that implement these interfaces. See the following section for details.

2. Enumeration type

<span style= "FONT-SIZE:14PX;" >enum Newstype {
	topnews,	//a
	SPORTS = 2,	//b
	tecnology = 3,
	NBA = 0xa,	//c
	EDU = 5< c8/>}	//d

struct News {  
	1:i32 id;  
	2:string title;  
	3:string content;  
	4:string Source;  
	5:string author;  
	6:double score;
	7:i64 Readnum;
	8:newstype newstype = newstype.sports; E
} </span>

Description
A. The compiler defaults to 0-based assignment
B. You can assign a constant to an integer
C. Allow constants to be hexadecimal integers
D. No comma at the end
E. When assigning a default value to a constant, use the full name of the constant
Note that unlike protocol Buffer,thrift does not support enumeration class nesting, enumeration constants must be 32-bit positive integers

2.3. Notes
Thrfit supports shell annotation styles, single-line or multiline annotation styles in C + + languages

# This is a valid comment.

/
 
* * This is a multi-line comment.
 
* Just like in C.
 
*
 
///C++/java style Single-line comments work just as well.

2.4. Namespaces
The namespaces in thrift are similar to the namespace in C + + and the package in Java, and they all provide a way to organize (isolate) code. Because each language has its own namespace definition (such as a module in Python), thrift allows developers to define namespace for a specific language:
<span style= "FONT-SIZE:14PX;" >namespace CPP Com.example.project  //A
namespace Java com.example.project//b
namespace py Com.example.project	//python
namespace php com.example.project  	//php</span>

Description
A. Convert to namespace Com {Namespace example {namespace Project {
B. Convert to package Com.example.project
2.5. The file contains
Thrift allows the thrift file to contain, the user needs to use the thrift file name as a prefix to access the contained objects, such as:
Namespace Java com.example.thrift.service

include "Newsmodel.thrift"	//a

service DataSource {  

	String HelloWorld (1:string name), 

	bool Indexnews (1:newsmodel.news indexnews),//b
	
	newsmodel.news Getnewsbyid (1:i32 newsId), 
	
	map<string,newsmodel.news> getnewsmap (1:i32 newstype), 
	
	list<newsmodel.news> Getnewslist (1:i32 newstype), 
}  

Description
A.thrift file names are enclosed in double quotes with no comma or semicolon at the end
B. Note Newsmodel prefix, IDL file name as prefix, not namespace

2.6. Define the structure body
A struct consists of a series of fields, each with a unique integer identifier, a type, a name, and an optional default parameter. Such as:

struct News {  
	1:required i32 ID;  A
	2:required string title;  b
	3:string content;  
	4:string Source;  
	5:string author;  
	6:double score = 4.2;	D
	7:i64 Readnum;
	8:newstype newstype = newstype.sports;
	10:optional user user;	C
} 


struct User {	//e
	1:required i32 ID; 
	2:required string userName;
 	3:required string password;
 	4:optional string Nickname; 

Description
A. Each domain has a unique, positive integer identifier
B. Each domain can be identified as required or optional (or may not be noted)
C. Struct can contain other structure body
D. Domains can have default values
E. Multiple structures can be defined in a thrift, and referential relationships exist
Each domain in the canonical struct definition is identified using the required or optional keyword. If the domain identified by required is not assigned a value, thrift will give you a hint. If the domain identified by optional is not assigned a value, the domain will not be serialized for transmission. If a optional identity domain has a default value and the user is not re-assigned, the value of that field is always the default value.
Unlike service, structs do not support inheritance, that is, a struct cannot inherit another struct.
2.7. Defining Services
In the popular serialization/deserialization framework (such as protocol buffer), thrift is a framework for providing multiple-language RPC services.
The thrift compiler generates the service interface code for the server based on the target language chosen, generating the stub code for the client.

Namespace Java com.example.thrift.service

include "Newsmodel.thrift"
//"DataSource" and "{" need to have spaces between ...
service DataSource {  

	string HelloWorld (1:string name), 	//a

	bool Indexnews (1:newsmodel.news indexnews), 	//b
	
	newsmodel.news Getnewsbyid (1:i32 newsId),//c
	
	map<string,newsmodel.news> Getnewsmap (1:i32 newstype), 
	
	list<newsmodel.news> getnewslist (1:i32 newstype), 
	
	//"OneWay" The identifier indicates that the client does not have to wait for a reply (non-blocking) to proceed directly after the request is made, 
	//The return value of the "OneWay" method must be void 
	oneway void zip ()   //D
}  

Description
A function definition can end with a comma or semicolon ID
b Parameters can be primitive types or structs, parameters are read-only (const), and cannot be returned as values ...
C The return value can be a basic type or struct
D The return value can be void
Note that the parameter list in the function is defined in exactly the same way as the struct
Service support inheritance, one service can use the extends keyword to inherit another service

C. Compile & Generate code
Windows Configuration Thrift Development Environment
1. Install thrift: Download EXE file to thrift website, download address: Http://thrift.apache.org/download. The file is then renamed to Thrift.exe, copied to the F:\thrift directory (or any directory), and can then be used in a DOS environment, as follows:
F:\thrift>thrift-gen java D:\mywork\javaProject\thriftTest\test.thrift, output Java file default output to the current directory F:\thrift, You can also specify an output path using the-o parameter.

The following issues occur when compiling in a Windows environment, as shown in the figure:


The original is the coding problem, the final unified Thrift file encoding for UTF-8 can be compiled through the normal.

Iv. writing client and service side
1. Download Dependent packages
A. Libthrift.jar
B. Slf4j-api.jar
C. Slf4j-simple.jar

2. Writing the interface implementation code

Package Com.example.thrift.impl;
Import java.util.List;

Import Java.util.Map;

Import org.apache.thrift.TException;
Import Com.example.thrift.model.News;

Import Com.example.thrift.service.DataSource; public class Datasourcehandler implements datasource.iface{@Override public string HelloWorld (string name) throws Texc
	eption {//TODO auto-generated method stub return "Hello" +name+ ", welcom to thrift!"; } @Override public boolean indexnews (News indexnews) throws Texception {//TODO auto-generated method stub return
	False
		} @Override Public News Getnewsbyid (int newsId) throws Texception {News news = new News ();
		News.setid (1000);
		News.setauthor ("Ricky Feng");
		
		News.setcontent ("Thrift Demo");
	return news;  } @Override public map<string, news> getnewsmap (int newstype) throws Texception {//TODO auto-generated method
	stub return null; } @Override public list<news> getnewslist (int newstype) throws Texception {//TODO Auto-geneRated method stub return null;
 }

}

3. Writing the server code

Package com.example.thrift;
Import Org.apache.thrift.TProcessor;
Import Org.apache.thrift.protocol.TBinaryProtocol;
Import Org.apache.thrift.server.TServer;
Import Org.apache.thrift.server.TSimpleServer;
Import Org.apache.thrift.transport.TServerSocket;
Import org.apache.thrift.transport.TTransportException;
Import Com.example.thrift.impl.DataSourceHandler;

Import Com.example.thrift.service.DataSource;

	public class HelloServer {public static final int server_port = 8090;
	public static void Main (string[] args) {startserver ();
			} private static void StartServer () {try {System.out.println ("HelloServer tsimpleserver start ...");
			Tprocessor tprocessor = new datasource.processor<datasource.iface> (new Datasourcehandler ());
			Simple single-threaded service model, typically used for testing tserversocket Servertransport = new Tserversocket (server_port);
			Tserver.args Targs = new Tserver.args (servertransport);
			Targs.processor (Tprocessor); Targs.protocolfactory (New Tbinaryprotocol.factory ());
			Tserver Server = new Tsimpleserver (Targs);
		Server.serve ();
		} catch (Ttransportexception e) {e.printstacktrace ();
 }

	}
}

4. Writing the client code

Package com.example.thrift;
Import org.apache.thrift.TException;
Import Org.apache.thrift.protocol.TBinaryProtocol;
Import Org.apache.thrift.protocol.TProtocol;
Import Org.apache.thrift.transport.TSocket;
Import Org.apache.thrift.transport.TTransport;

Import org.apache.thrift.transport.TTransportException;

Import Com.example.thrift.service.DataSource;
	
	public class Helloclient {public static final String server_ip = "localhost";
	
	public static final int server_port = 8090;

	public static final int TIMEOUT = 30000;
	public static void Main (string[] args) {startclient ();
		
		} private static void Startclient () {Ttransport transport = null;
			
			try {System.out.println ("helloclient start ...");
			Transport = new Tsocket (server_ip, Server_port, TIMEOUT);
			Agreement to be consistent with the server Tprotocol protocol = new Tbinaryprotocol (transport);
			Tprotocol protocol = new Tcompactprotocol (transport);
			Tprotocol protocol = new Tjsonprotocol (transport); Datasource.client Client = new Datasource.client (protocol);
			Transport.open ();
			String result = Client.helloworld ("Ricky");
		SYSTEM.OUT.PRINTLN ("thrify Client result =:" + result);
		} catch (Ttransportexception e) {e.printstacktrace ();
		} catch (Texception e) {e.printstacktrace ();
			} finally {if (null! = Transport) {transport.close ();
 }
		}
	}
}


Run the HelloServer startup service first, and then run helloclient to see the console print:

Helloclient start ....
Thrify client result =: Hello ricky,welcom to thrift! Indicates that the client invocation succeeded.

For a detailed example of thrift use, refer to the tutorial on the Apache Thrift website, address: Http://thrift.apache.org/tutorial/java



Finally attach the sample code download address: http://download.csdn.net/detail/fx_sky/7499361




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.