小白入门Thrift RPC框架
Posted 柚子聊大数据
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了小白入门Thrift RPC框架相关的知识,希望对你有一定的参考价值。
一、准备工作
thrift是跨语言的RPC框架,需要通过thrift compiler将thrift idl编译成java代码,因此在使用thrift框架时需要在PC机上安装thrift compiler。笔者使用的Mac Pro,安装步骤如下:
安装brew(亲测有用)
/bin/zsh -c "$(curl -fsSL https://gitee.com/cunkai/HomebrewCN/raw/master/Homebrew.sh)"
安装thrift
# 安装的是最新版本;最简单方式;
brew install thrift
引入依赖包
<dependency>
<groupId>org.apache.thrift</groupId>
<artifactId>libthrift</artifactId>
<version>0.14.1</version>
</dependency>
本文以两个int类型相加为例,给予说明。
二、具体过程
书写idl,并编译
namespace java com.zte
service CalculateService{
i32 calculate(1:i32 a,2:i32 b)
}
编译命令
thrift -r -gen java staff.thrift
创建com.zte package,并将CalculateService类拷贝到该package下。
实现Service接口
此案例接收两个整形参数并进行相加。
package com.zte.impl;
import com.zte.CalculateService;
import org.apache.thrift.TException;
public class CalculateServiceImpl implements CalculateService.Iface {
@Override
public int calculate(int a, int b) throws TException {
return a+b;
}
}
服务端代码
package thrift.server;
import com.zte.CalculateService;
import com.zte.impl.CalculateServiceImpl;
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;
public class CalculateServer {
public static void main(String[] args) throws TTransportException {
System.out.println(Thread.currentThread().getName()+"server begin to start.");
TServerSocket serverSocket = new TServerSocket(8088);
TServer.AbstractServerArgs arg = new TServer.Args(serverSocket);
CalculateService.Processor processor = new CalculateService.Processor<CalculateService.Iface>(new CalculateServiceImpl());
arg.processor(processor);
arg.protocolFactory(TBinaryProtocol::new);
TSimpleServer simpleServer = new TSimpleServer(arg);
simpleServer.serve();
System.out.println(Thread.currentThread().getName()+"server started");
}
}
客户端代码
package thrift.client;
import com.zte.CalculateService;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.transport.TSocket;
public class CalculateClient {
public static void main(String[] args) throws TException {
System.out.println("client begin to start");
TSocket tSocket = new TSocket("127.0.0.1",8088);
TBinaryProtocol protocol = new TBinaryProtocol(tSocket);
CalculateService.Client client = new CalculateService.Client(protocol);
tSocket.open();
System.out.println(Thread.currentThread().getName() +" calculate :" + client.calculate(10,12));
}
}
以上是关于小白入门Thrift RPC框架的主要内容,如果未能解决你的问题,请参考以下文章