实战环境
- win10
- IDEA 2018.1.6
- JDK 1.8
- thrift 0.11.0
- spring-boot 2.2.1
创建Thrift项目
- 创建Thrift项目
- 编译thrift文件,导出成java文件,并将编译导出的java文件打成jar包,作为Thrift API
创建Thrift项目
新建一个maven项目,在src/main
包下创建thrift
文件夹和java
文件夹,在thrift文件夹下编写RPCDateService.thrift
文件。我们可以编写如下接口:
namespace java com.wl.thrift.api
service RPCDateService{
string getDate(1:string userName)
}
pom文件需要添加以下依赖和插件
<dependencies>
<dependency>
<groupId>org.apache.thrift</groupId>
<artifactId>libthrift</artifactId>
<version>0.11.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.thrift.tools</groupId>
<artifactId>maven-thrift-plugin</artifactId>
<version>0.1.11</version>
<configuration>
<!--<thriftExecutable>/usr/local/bin/thrift</thriftExecutable>-->
<!--<thriftSourceRoot>src/main/thrift</thriftSourceRoot>-->
<outputDirectory>src/main/java</outputDirectory>
<generator>java</generator>
</configuration>
<executions>
<execution>
<id>thrift-sources</id>
<phase>generate-sources</phase>
<goals>
<goal>compile</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
ps:
- thrift文件需要编译,采用的是
maven-thrift-plugin
插件 libthrift
依赖的版本需要和本地安装的Thrift服务版本相同,否则编译报错。安装见上一篇文章maven-thrift-plugin
插件的执行compile
阶段绑定generate-sources阶段。
为什么要绑定在这个阶段?而不是compile阶段呢?因为我们thrift插件的作用是生成java文件,而在maven执行compile阶段时,java文件必须生成完毕才能进行编译,因此,该插件的执行必须在compile之前,所以放在generate-sources阶段比较合适。
thriftExecutable:指的是thrift编译器的位置,如果我们配置了环境变量,可以不指定。验证环境变量可以使用thrift --version命令。
thriftSourceRoot:thrift源文件的目录,默认会从src/main/thrift下读取。
outputDirectory:生成java文件的目录。其实这个一般不需要配置,因为java文件的包名是在.thrift文件以namespace的形式定义的。
编译thrift文件,导出成java文件,并打成jar包
在IDEA底部的Terminal工具中输入mvn clean install
命令进行打成jar包。
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-WdfmwNav-1574604513328)(/image/ThriftAPI.png)]
开发Thrift服务端
采用sprint-Boot编写服务端
创建spring-boot项目
在pom文件
中导入依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.wl</groupId>
<artifactId>ThriftAPI</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.apache.thrift</groupId>
<artifactId>libthrift</artifactId>
<version>0.11.0</version>
</dependency>
</dependencies>
创建controller实现Thrift API接口
创建controller
文件夹,创建RPCDateServiceIml.java
文件,内容如下:
package com.wl.controller;
import com.wl.thrift