下载编译器
http://thrift.apache.org/download
配置环境变量
下载完成后改名为thrift
在环境变量path中添加路径
验证
thrift --version
在idea中创建.thrift文件
namespace java thrift
.generated
typedef i16
short
typedef i32
int
typedef i64
long
typedef bool
boolean
typedef string String
struct Person
{
1:optional String userName
,
2:optional
int age
,
3:optional
boolean married
}
exception DataException
{
1:optional String message
,
2:optional String callStack
,
3:optional String date
}
service PersonService
{
Person
getPersonByUserName(1:required String userName
) throws (1:DataException dataException
),
void savePerson(1:required Person person
) throws(1:DataException dataException
)
}
编译
编写实现类
public class PersonServiceImpl implements PersonService.Iface {
@Override
public Person
getPersonByUserName(String userName
) throws TException
{
System
.out
.println("userName:"+userName
);
Person person
=new Person();
person
.setUserName(userName
);
person
.setAge(14);
person
.setMarried(false);
return person
;
}
@Override
public void savePerson(Person person
) throws TException
{
System
.out
.println("person:"+person
);
System
.out
.println(person
.getUserName());
System
.out
.println(person
.getAge());
System
.out
.println(person
.isMarried());
}
}
编写服务端
public class ThriftServer {
public static void main(String
[] args
) throws TTransportException
{
TNonblockingServerSocket socket
=new TNonblockingServerSocket(8899);
THsHaServer
.Args arg
=new THsHaServer.Args(socket
).minWorkerThreads(2).maxWorkerThreads(4);
PersonService
.Processor
<PersonServiceImpl> processor
=new PersonService.Processor<>(new PersonServiceImpl());
arg
.protocolFactory(new TCompactProtocol.Factory());
arg
.transportFactory(new TFastFramedTransport.Factory());
arg
.processorFactory(new TProcessorFactory(processor
));
TServer server
=new THsHaServer(arg
);
System
.out
.println("thrift server started!");
server
.serve();
}
}
编写客户端
public class ThriftClient {
public static void main(String
[] args
) {
TTransport transport
= new TFastFramedTransport(new TSocket("localhost", 8899), 600);
TProtocol protocol
= new TCompactProtocol(transport
);
PersonService
.Client client
= new PersonService.Client(protocol
);
try {
transport
.open();
Person person
= client
.getPersonByUserName("张三");
System
.out
.println(person
.getUserName());
Person p
=new Person();
p
.setUserName("李四");
p
.setAge(14);
p
.setMarried(true);
client
.savePerson(p
);
} catch (Exception e
) {
e
.printStackTrace();
} finally {
transport
.close();
}
}
}