Apache Thrift with Java Quickstart (Thrift introduction and Java instance)

Source: Internet
Author: User

    thrift是一个软件框架,用来进行可扩展且跨语言的服务的开发。它结合了功能强大的软件堆栈和代码生成引擎,以构建在 C++, Java, Python, PHP, Ruby, Erlang, Perl, Haskell, C#, Cocoa, JavaScript, Node.js, Smalltalk, and OCaml 这些编程语言间无缝结合的、高效的服务。
1. Overview

Thrift was originally developed by Facebook, open source in April 07 and entered the Apache incubator in May 08. Thrift allows you to define a simple definition of the data type in the file and the service interface. As an input file, the compiler generates code to easily build a seamless cross-programming language for RPC client and server communication.

Website address: thrift.apache.org
Recommended Articles worth reading:
http://thrift.apache.org/
Http://thrift.apache.org/download
Http://jnb.ociweb.com/jnb/jnbJun2009.html
Http://wiki.apache.org/thrift

2. Maven Dependency

If it is a MAVEN build project, add the following directly to the Pom.xml:

<dependency>  <groupId>org.apache.thrift</groupId>  <artifactId>libthrift</artifactId>  <version>0.9.2</version></dependency>
3. Basic Concepts

3.1. Data type

Basic type:
BOOL: Boolean, True or False, Boolean corresponding to Java
A byte:8-bit signed integer that corresponds to the byte of Java
I16:16-bit signed integer that corresponds to the short of Java
I32:32-bit signed integer that corresponds to the int of Java
i64:64-bit signed integer that corresponds to a long in Java
double:64 bit floating point number, corresponding to the double of Java
STRING:UTF-8 encoded string that corresponds to Java string
struct type:
struct: Defines a common object, similar to a struct definition in C, which is a JavaBean in Java
Container type:
List: ArrayList for Java
Set: corresponding to Java HashSet
Map: HashMap for Java
Exception type:
Exception: Exception for Java
Service Type:
Service: The class of the corresponding services
3.2. Server-side Coding basic steps:

Implement the service Processing interface Impl
Create Tprocessor
Create Tservertransport
Create Tprotocol
Create Tserver
Start the server
3. Basic client code steps:

Create transport
Create Tprotocol
Create a Client based on Ttransport and Tprotocol
The corresponding method of calling the client
4. Data Transfer Protocol

Tbinaryprotocol: binary format.
Tcompactprotocol: Compression format
Tjsonprotocol:json format
Tsimplejsonprotocol: Provides JSON write-only protocol, resulting files are easily parsed by scripting language
Tips: The client and server protocols are consistent

4. Example Demonstration

Before you have to install thrift, you can install on Windows, you can install on Linux, as long as you can execute the thrift command to produce the service-side interface on the line.

4.1. Add a file Add.thrift, which contains the following content:

If you have used Google Protocol buffer, you will not be unfamiliar with the following operations.

namespace java com.jamesfen.thrift  // java的包名     typedefint  //typedefs to get convenient names for your types     service AdditionService {  // defines the service to add two numbers     int add(1:int2:int//defines a method }

4.2. Generate the service-side interface code and execute the following command

add.thrift

4.3. Implementing the interface
When you are done with the second step, the current directory will produce a Gen-java folder containing a Additionservice.java file to copy the class into your package. There is an internal interface to implement, and now you want to implement that interface.

package com.jamesfen.thrift;import org.apache.thrift.TException;publicclass AdditionServiceHandler implements AdditionService.Iface{    @Override    publicintadd(intintthrows TException {      return n1 + n2;    }}

4.4. Service-side code, open a listening interface for the Additionservicehandler class (9090)

Packagecom. Jamesfen. Thrift;import org. Apache. Thrift. Transport. Tserversocket;import org. Apache. Thrift. Transport. Tservertransport;import org. Apache. Thrift. Server. Tserver;import org. Apache. Thrift. Server. Tserver. Args;import org. Apache. Thrift. Server. Tsimpleserver;public class MyServer {public static void Startsimpleserver (Additionservice. Processor<AdditionServiceHandler> processor) {try {tservertransport servertransport = new Tserversocket (9090);Tserver Server = new Tsimpleserver (new Args (Servertransport). Processor(processor));Use the this for a multithreaded server//Tserver server = new Tthreadpoolserver (New//Tthreadpools Erver. Args(Servertransport). Processor(processor));System. out. println("Starting the simple server ...");Server. Serve();} catch (Exception e) {E. Printstacktrace();}} public static void Main (string[] args) {startsimpleserver (new Additionservice. Processor<AdditionServiceHandler> (New Additionservicehandler ()));}}

5. Client code, requesting service

Packagecom. Jamesfen. 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;public class Additionclient {public static void main (string[] args) {try {Ttransport transport;Transport = new Tsocket ("localhost",9090);Transport. Open();Tprotocol protocol = new Tbinaryprotocol (transport);Additionservice. ClientClient = new Additionservice. Client(protocol);System. out. println(Client. Add( -, $));Transport. Close();} catch (Ttransportexception e) {E. Printstacktrace();} catch (Texceptionx) {x. Printstacktrace();}    }}

4.6. Running results
Service side:
Starting the simple server ...
Client:
300
4.7:demo Source
Https://github.com/Bellonor/myhadoop2.x/tree/master/myhadoop2.x/src/main/java/com/jamesfen/thrift

Apache Thrift with Java Quickstart (Thrift introduction and Java instance)

Related Article

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.