本篇介绍Apache thrift windows安装教程。

一.首先在Apache官网下载thrift 编译应用,戳这里下载 http://thrift.apache.org/download

    下载好windows 版本的exe文件。在c盘新建一个Thrift文件夹,将下载好的thrift-xxx.exe文件该名成 thrift.exe,放入Thrift文件夹中。

二.配置环境变量

    Apache thrift 安装及使用

 

 然后运行cmd命令,输入 thrift  -version。看到如下版本信息,则表示thrift 安装成功。

Apache thrift 安装及使用

是不是很easy! 接下来就可以干正事了。

三.编写thrift脚本文件,生产对应语言的代码,此处我使用java作为案例。

namespace java com.zhj.thrift.server  // defines the namespace   

typedef i32 int  //typedefs to get convenient names for your types  
typedef i16 short
typedef i64 long

service HelloService{
    int add(1:int num1,2:int num2)
    short getShort(1:short value)
    long getLong(1:long value)
    string sayHello(1:string name)

}

保存该文件命名为:helloService.thrift。之后执行该文件会生成一个helloService接口的java代码.

四.找到上述文件的目录,执行该文件。执行后会在相同的目录下生成一个gen-java的包。里面就生产了helloService.java的一个类

Apache thrift 安装及使用

五.新建一个Java 项目,将上述接口拷到项目中,并实现该接口。实现接口类如下:

package com.zhj.thrift.server.impl;

import org.apache.thrift.TException;
import com.zhj.thrift.server.HelloService;

public class HelloServiceImpl implements HelloService.Iface {

    @Override
    public int add(int num1, int num2) throws TException {
        return num1+num2;
    }

    @Override
    public short getShort(short value) throws TException {
        return (short) (value*2);
    }

    @Override
    public long getLong(long value) throws TException {
        Long l_value = value - 24*60*60*1000;
        return l_value;
    }

    @Override
    public String sayHello(String name) throws TException {
        return "hello " + name;
    }

}
View Code

相关文章: