本文共 3116 字,大约阅读时间需要 10 分钟。
代码在GitHub上托管
创建IDL文件hw.thrift
namespace java com.test.thriftnamespace go pkg.servicestruct Data { 1: string text;}service format_data { Data doFormat(1:Data data);}
生成的代码报错,是由于缺少libthrift库引起的,因此在pom.xml文件中,添加必要的依赖
hw-thrift com.test.thrift 1.0-SNAPSHOT 4.0.0 java-thrift-idl org.apache.thrift libthrift 0.11.0 org.apache.maven.plugins maven-compiler-plugin 3.7.0
</project>
- 添加完依赖@Override 注解报错的话,可能是由于thrift的版本不一致引起的。## 创建go模块,用于存储生成go版本的代码库 - 利用thrift来生成go版本的代码库 thrift --gen go -out ../go-thrift-idl hw.thrift![](https://note.youdao.com/yws/public/resource/9c8584c6ec980aee585665c38a65bf9d/xmlnote/42EAB0BE237340D6A8989EEF383753DE/20079)- 注意生成的代码是有问题的[原因具体不详] - 在hw.go文件中 oprot.Flush()抛异常,not enough arguments in call to oprot.Flush less... (Ctrl+F1) - 解决措施:原因是缺少context.Context类型的参数,刚好方法中已经有,直接添加上就可以了,改成oprot.Flush(ctx) - 将生成的代码库pkg 拷贝到gopath的src路径下,这样客户端就可以使用代码库了,不然有可能找不到生成的代码库## 创建maven模块,用于创建服务端 - 创建maven模块,java-thrift-server - 更新pom.xml文件,添加对java-thrift-idl的依赖 - 编写FormatDataImpl实现hw.thrift定义的接口- 编写sever, 实现thrift编程## 创建go模块,用于go版本的客户端 - 创建go模块,go-thrift-client - 编写业务逻辑## 测试 - 启动服务器端 - 启动客户端 > 将服务端更改spring-boot 版本 > 也就是更新java-thrift-server 模块 - 更新java-thrift-server模块的pom文件,为下面的形式
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns=""xmlns:xsi=""xsi:schemaLocation=" ;<!-- 添加spring-boot--><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>1.5.3.RELEASE</version></parent><modelVersion>4.0.0</modelVersion>java-thrift-server org.springframework.boot spring-boot-starter com.test.thrift java-thrift-idl 1.0-SNAPSHOT
</project>
- 添加appliaction.properties配置文件 > server.name=java-thrift-service server.port=8082 - 更新FormatDataImpl文件,添加@Service注解,也就是交给spring 管理起来 - 创建thirift_socket包,创建ThriftServer文件,编写Thrift逻辑 - 可能会报错,如果是could not autowire. no bean of Iface的话,可以不用管 - 更新server文件,添加上@SpringBootApplication 注解,表明是启动类 - 测试 > 启动服务端 启动客户端
转载于:https://blog.51cto.com/xingej/2167067