search
HomeDatabaseMysql TutorialApache Thrift入门2-Java代码实现例子

Apache Thrift入门2-Java代码实现例子

Jun 07, 2016 pm 04:26 PM
apachethriftcodegetting Startedaccomplish

在上一篇文章中提到了Thrift的架构、传输协议(Ref),本篇文章将对Thrift的入门实例进行介绍。 分为如下5个部分: 运行环境、安装/配置、脚本文件、创建代码、运行程序。 一、开发环境(清单1) 1.操作系统 Server-Linux / Client-WinXP 2.SDK Sun JDK1.5+ 3.需

  在上一篇文章中提到了Thrift的架构、传输协议(Ref),本篇文章将对Thrift的入门实例进行介绍。 分为如下5个部分: 运行环境、安装/配置、脚本文件、创建代码、运行程序。

一、开发环境(清单1)
1.操作系统
    Server-Linux / Client-WinXP
2.SDK
    Sun JDK1.5+

3.需要的jar依赖包
    libthrift.jar
    slf4j-api-1.5.8.jar
    slf4j-log4j12-1.5.8.jar
    log4j-1.2.15.jar

4.编译工具
    Apache Ant  & Apache ivy

二、安装/配置 (清单2)
    1.下载thrift源文件
        http://labs.renren.com/apache-mirror//incubator/thrift/0.5.0-incubating/thrift-0.5.0.tar.gz
        
    2.编译thrift源文件
        1)解压 thrift-0.5.0.tar.gz
        2)用ant编译源代码,进入x:\thrift-0.5.0\lib\java目录,执行ant,通过ant中的ivy工具会自动从站点下载所需要的依赖包,编译完成后如图所示:
         http://zcitrq.bay.livefilestore.com/y1pA4vlwBHBEPK_vNd4oVbU_egUdTTdw7fKAW_rmoBiqEg-ZO8rfDednCMCylQqrM1SpKVOp49bbbD0rfMhiaRHwq93o5RHaQUG/complie-thirtf.png?psid=1
        3)编译过程中下载的依赖包在x:\thrift-0.5.0\lib\java\build\ivy\lib 目录下可以看见下载的jar依赖包,将编译成功以后的jar包加入Eclipse的开发环境中。

三、脚本文件(清单3)
    1.创建脚本
        创建脚本文件 testJava.thrift ,脚本文件内容如下:
        namespace java com.javabloger.gen.code   # 注释1   定义生成代码的命名空间,与你需要定义的package相对应。

        struct Blog {   #  注释2.1   定义实体名称和数据结构,类似你业务逻辑中的pojo get/set
            1: string topic     #  注释2.2  参数类型可以参见 Thrift wiki  
            2: binary content  
            3: i64    createdTime
            4: string id
            5: string ipAddress
            6: map props
          }
        service ThriftCase {  #  注释3    代码生成的类名,你的业务逻辑代码需要实现代码生成的ThriftCase.Iface接口
            i32 testCase1(1:i32 num1, 2:i32 num2, 3:string  num3) #注释4.1 方法名称和方法中的入参,入参类型参见wiki
            list testCase2(1:map  num1)
            void testCase3()
            void testCase4(1:list blog)   #  注释4.2   list 是thrift中基本数据类型中的一种,list中包含的Blog对象是上面struct中定义的
        }

    2.运行脚本
        1)从 thrift 站点下载windows版本的编译工具,下载地址:http://labs.renren.com/apache-mirror//incubator/thrift/0.5.0-incubating/thrift-0.5.0.exe
        2)通过Thrift的脚本文件,运行 thrift 命令创建生成的代码,例如:执行 thrift -gen java x:\testJava.thrift  命令,在当前运行的盘符下,可看见gen-java目录,在这里目录中可以看见生成的java代码,更多thrift 命令内容,请参见thrift命令自带的help。

3.Thrift 中的基本数据类型 (清单4)
    类型 描述
bool true, false
byte 8位的有符号整数
i16 16位的有符号整数
i32 32位的有符号整数
i64 64位的有符号整数
double 64位的浮点数
string UTF-8编码的字符串
binary 字符数组
struct 结构体
list 有序的元素列表,类似于STL的vector
set 无序的不重复元素集,类似于STL的set
map key-value型的映射,类似于STL的map
exception 是一个继承于本地语言的exception基类
service 服务。包含多个函数接口(纯虚函数)

四、创建代码(清单5)
    我将示例工程分了4个包,如下所示:
     \com\javabloger
            \client               # 1.客户端测试代码
            \gen\code              # 2.通过脚本生成的class
            \layer\transport       # 3.服务器端代码和定义的传输协议
            \layer\business      # 4.具体的业务逻辑代码
    具体代码内容这里就不阐述了,重点是要明白代码的结构和层次关系,其次是里面主要的几个类的含义,至于代码是怎么写的并不是非常重要,仅仅是我个人观点,仅供参考,谢谢。

代码示例的下载地址: http://javabloger-mini-books.googlecode.com/files/Thritf.zip

五、运行程序
    先运行server,再运行client ,客户端向服务器端发送数据调用服务器端的4个方法,服务器端被传入客户端数据,运行效果如图所示:
    run-thirtf-code.png

相关文章:
Apache Thrift入门1-架构&介绍

–end–
 

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
MySQL: BLOB and other no-sql storage, what are the differences?MySQL: BLOB and other no-sql storage, what are the differences?May 13, 2025 am 12:14 AM

MySQL'sBLOBissuitableforstoringbinarydatawithinarelationaldatabase,whileNoSQLoptionslikeMongoDB,Redis,andCassandraofferflexible,scalablesolutionsforunstructureddata.BLOBissimplerbutcanslowdownperformancewithlargedata;NoSQLprovidesbetterscalabilityand

MySQL Add User: Syntax, Options, and Security Best PracticesMySQL Add User: Syntax, Options, and Security Best PracticesMay 13, 2025 am 12:12 AM

ToaddauserinMySQL,use:CREATEUSER'username'@'host'IDENTIFIEDBY'password';Here'showtodoitsecurely:1)Choosethehostcarefullytocontrolaccess.2)SetresourcelimitswithoptionslikeMAX_QUERIES_PER_HOUR.3)Usestrong,uniquepasswords.4)EnforceSSL/TLSconnectionswith

MySQL: How to avoid String Data Types common mistakes?MySQL: How to avoid String Data Types common mistakes?May 13, 2025 am 12:09 AM

ToavoidcommonmistakeswithstringdatatypesinMySQL,understandstringtypenuances,choosetherighttype,andmanageencodingandcollationsettingseffectively.1)UseCHARforfixed-lengthstrings,VARCHARforvariable-length,andTEXT/BLOBforlargerdata.2)Setcorrectcharacters

MySQL: String Data Types and ENUMs?MySQL: String Data Types and ENUMs?May 13, 2025 am 12:05 AM

MySQloffersechar, Varchar, text, Anddenumforstringdata.usecharforfixed-Lengthstrings, VarcharerForvariable-Length, text forlarger text, AndenumforenforcingdataAntegritywithaetofvalues.

MySQL BLOB: how to optimize BLOBs requestsMySQL BLOB: how to optimize BLOBs requestsMay 13, 2025 am 12:03 AM

Optimizing MySQLBLOB requests can be done through the following strategies: 1. Reduce the frequency of BLOB query, use independent requests or delay loading; 2. Select the appropriate BLOB type (such as TINYBLOB); 3. Separate the BLOB data into separate tables; 4. Compress the BLOB data at the application layer; 5. Index the BLOB metadata. These methods can effectively improve performance by combining monitoring, caching and data sharding in actual applications.

Adding Users to MySQL: The Complete TutorialAdding Users to MySQL: The Complete TutorialMay 12, 2025 am 12:14 AM

Mastering the method of adding MySQL users is crucial for database administrators and developers because it ensures the security and access control of the database. 1) Create a new user using the CREATEUSER command, 2) Assign permissions through the GRANT command, 3) Use FLUSHPRIVILEGES to ensure permissions take effect, 4) Regularly audit and clean user accounts to maintain performance and security.

Mastering MySQL String Data Types: VARCHAR vs. TEXT vs. CHARMastering MySQL String Data Types: VARCHAR vs. TEXT vs. CHARMay 12, 2025 am 12:12 AM

ChooseCHARforfixed-lengthdata,VARCHARforvariable-lengthdata,andTEXTforlargetextfields.1)CHARisefficientforconsistent-lengthdatalikecodes.2)VARCHARsuitsvariable-lengthdatalikenames,balancingflexibilityandperformance.3)TEXTisidealforlargetextslikeartic

MySQL: String Data Types and Indexing: Best PracticesMySQL: String Data Types and Indexing: Best PracticesMay 12, 2025 am 12:11 AM

Best practices for handling string data types and indexes in MySQL include: 1) Selecting the appropriate string type, such as CHAR for fixed length, VARCHAR for variable length, and TEXT for large text; 2) Be cautious in indexing, avoid over-indexing, and create indexes for common queries; 3) Use prefix indexes and full-text indexes to optimize long string searches; 4) Regularly monitor and optimize indexes to keep indexes small and efficient. Through these methods, we can balance read and write performance and improve database efficiency.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment