栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Apache Thrift:简单的使用demo

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Apache Thrift:简单的使用demo

当前版本:jdk1.8、thrift 0.16.0

1. 声明

当前内容主要简单的使用thrift实现客户端和服务端,主要从apache iotdb中得知,详情可以查看官方

1. 下载thrift(apache 官方访问不是很好可以直接使用华为mirror)

下载即可(本人使用exe的,建议也下载gz的,gz的中有tutorial)

2. 使用官方的Demo

1.将gz中的tutorial中的shade.thrift和tutorial.thrift拷贝到thrift-0.16.0.exe同级目录下

2.使用cmd并执行:thrift-0.16.0.exe -r --gen java tutorial.thrift

此时在该目录下会生成gen-java文件并会生成对应的代码

3. 将gz中的tutorial中的java内src内容部分考入到项目,同时将上面生成的也放入项目中

4. 修改部分JavaClient和JavaServer中的代码(只使用simple即可)

5. 启动JavaServer然后在启动JavaClient结果如下



发现执行成功!通过查看代码和tutorial.thrift文件可以得到具体实现

3. 模仿并实现自己的HiService

1. 创建test.thrift

// 定义一个服务就是HiService
service HiService {
   void hello()
}

2. 使用命令生成HiService.java文件

3. 实现HiService中的Iface(即server端的处理)

public class HiServiceHandler implements HiService.Iface{
	@Override
	public void hello() throws TException {
		System.out.println("hello called !");
	}
}

4. 编写HiServiceServer和HiServiceClient

public class HiServiceClient {
	public static void main(String[] args) {
		TTransport transport;
		try {
			transport = new TSocket("localhost", 9090);
			transport.open();
			TProtocol protocol = new TBinaryProtocol(transport);
			HiService.Client client = new HiService.Client(protocol);

			client.hello();
			System.out.println("send msg to HiServiceServer!");
			transport.close();
		} catch (TException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}
public class HiServiceServer {
	public static void main(String[] args) {
		
		HiServiceHandler handler = new HiServiceHandler();
		TProcessor processor = new HiService.Processor(handler);
		try {
			TServerTransport serverTransport = new TServerSocket(9090);
			TServer server = new TSimpleServer(new Args(serverTransport).processor(processor));
			System.out.println("Starting the simple server...");
			server.serve();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

5. 测试


实现客户端和服务端非常容易

4. 总结

1. thrift使用thrift来限定当前的客户端和服务端的交流,可以快速实现rpc通信程序

2. 必须使用thrift特定的语法方式实现,必须学会定义

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/937783.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号