【maven】maven-thrift-plugin 插件使用 + Java项目中thrift使用的正确姿势

1.首先介绍下maven-thrift-plugin插件在java中使用

该插件可以让我们在maven中使用 编译.thrift文件,在大型项目中尤其有用。下面看下如何使用:

假设这里要提供一个HelloService的thrift服务:

namespace java com.liyao.service
service HelloService{
    string helloString(1:string para)
}

然后新建一个maven的项目,在src/main下新建一个thrift的目录存放我们的所有.thrift文件,然后在该目录下新建上面的HelloService.thrift。目录结构如下:


接着需要在pom中导入依赖和编译的插件。

(1)因为我们这里要生成thrift对应的java文件,所以一定要导入thrift相关的依赖,也就是libthrift的jar包;

(2)原生的maven并不会为我们编译thrift文件,所以需要在build中加入maven-thrift-plugin插件;

所以maven的pom文件如下:

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.liyao</groupId>
  <artifactId>thrift_plugin_project</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>thrift_project</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>

  <dependencies>
    <!-- https://mvnrepository.com/artifact/org.apache.thrift/libthrift -->
    <dependency>
      <groupId>org.apache.thrift</groupId>
      <artifactId>libthrift</artifactId>
      <version>0.9.3</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>-->
              </configuration>
              <executions>
                  <execution>
                      <id>thrift-sources</id>
                      <phase>generate-sources</phase>
                      <goals>
                          <goal>compile</goal>
                      </goals>
                  </execution>
                  <!--<execution>-->
                      <!--<id>thrift-test-sources</id>-->
                      <!--<phase>generate-test-sources</phase>-->
                      <!--<goals>-->
                          <!--<goal>testCompile</goal>-->
                      <!--</goals>-->
                  <!--</execution>-->
              </executions>
          </plugin>
      </plugins>
  </build>
</project>

在插件部分,我们执行了插件的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的形式定义的。

所以上面的pom文件没有做任何配置。

接着执行:

mvn clean install 命令即可生成一个jar包。


随后,我们就可以在自己的项目中通过依赖的方式引入生成的java文件。


再新建一个项目,该项目使用之前的jar文件:

pom:

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.liyao</groupId>
    <artifactId>thrift_project</artifactId>
    <version>1.0-SNAPSHOT</version>

    <name>thrift_project</name>
    <!-- FIXME change it to the project's website -->
    <url>http://www.example.com</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>com.liyao</groupId>
            <artifactId>thrift_plugin_project</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.apache.thrift/libthrift -->
        <dependency>
            <groupId>org.apache.thrift</groupId>
            <artifactId>libthrift</artifactId>
            <version>0.9.3</version>
        </dependency>
    </dependencies>
</project>

服务实现类:

import com.liyao.service.HelloService;
import org.apache.thrift.TException;

public class HelloServiceImpl implements HelloService.Iface {
    @Override
    public String helloString(String s) throws TException {
        return s;
    }
}

启动服务:

import com.liyao.service.HelloService;
import org.apache.thrift.TProcessor;
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 Server {
    public static void main(String args[]){
        try {
            System.out.println("服务端开启....");
            TProcessor tprocessor = new HelloService.Processor<HelloService.Iface>(new HelloServiceImpl());
            TServerSocket serverTransport = new TServerSocket(50005);
            TServer.Args tArgs = new TServer.Args(serverTransport);
            tArgs.processor(tprocessor);
            tArgs.protocolFactory(new TBinaryProtocol.Factory());
            TServer server = new TSimpleServer(tArgs);
            server.serve();
        }catch (TTransportException e) {
            e.printStackTrace();
        }
    }
}

客户端测试:

import com.liyao.service.HelloService;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;

public class Client {

    public static void main(String[] args) {
        System.out.println("客户端启动....");
        TTransport transport = null;
        try {
            transport = new TSocket("localhost", 50005);
            TProtocol protocol = new TBinaryProtocol(transport);
            HelloService.Client client = new HelloService.Client(protocol);
            transport.open();
            String result = client.helloString("liyao");
            System.out.println(result);
        } catch (TTransportException e) {
            e.printStackTrace();
        } catch (TException e) {
            e.printStackTrace();
        } finally {
            if (null != transport) {
                transport.close();
            }
        }
    }
}

2.Java项目中使用thrift:

第一次学习java thrift的时候,我们都是手动运行thrift编译器,然后把生成的java文件复制进自己的项目中使用。但是这种方式在大型项目中不可取。

一是因为thrift编译器的执行操作应该放在公共的机器上而不是每一个开发者在本地运行,本地运行可能导致很多不一致问题,如版本等。

二是从开发角度来说,thrift文件本质定义的是一个接口,接口的实现方和使用方可能会同时开发,那么比较好的流程是,双方约定好thrift的接口和参数,然后由一方编写thrift文件,双方评审,通过之后,把thrift文件按照开始介绍的方式打成jar包再部署到maven的仓库中。当然这个过程可能会引入版本控制等过程,可以把所有的thrift接口放在一个公共的项目中。如果新增一个接口,git会新增一个版本,然后通过部署工具部署到生产环境,部署工具后台会执行maven的一命令,把生成的jar文件部署到maven仓库。这样,双方在各自的项目中只需要以dependence的方式引入接口的jar包,各自开发即可,互不影响。


最后附上插件的github:https://github.com/dtrott/maven-thrift-plugin

顺便记录关键部分:

***************************
*** ONGOING MAINTENANCE ***
***************************

PLEASE NOTE: THIS CODE HAS BEEN CONTRIBUTED BACK TO ASF.

https://issues.apache.org/jira/browse/THRIFT-1536

Any future work I do on this plugin, will be as patches submitted to their version.
I am not planning to perform any further maintenance on this fork (or accept any patches / pull requests).

***********************
*** VERSION WARNING ***
***********************

Drop to the command line and type:

 thrift -version

To find out what version of the compiler you are using.


Older Compiler Versions (Less than 0.7.0)
===
You must use version 0.1.10 of this plugin.
+ Check out the source.
+ Switch to the old branch: git checkout -b old maven-thrift-plugin-0.1.10

And build/use that version.



Newer Compiler Versions (0.7.0 or newer)
===
0.7.0 should work fine with the latest version of this plugin.
However I have seen incompatibilities between the compiler and libthrift.

To resolve these check out the source for the compiler from the 0.7.0 branch (Do not trust the TAR BALLS)

svn co http://svn.apache.org/repos/asf/thrift/tags/thrift-0.7.0

That version should work fine with the maven version of lib thrift:

        <dependency>
            <groupId>org.apache.thrift</groupId>
            <artifactId>libthrift</artifactId>
            <version>0.7.0</version>
        </dependency>


Note: If you have problems building on OSX you might want to look at this article:

http://lueb.be/2009/02/23/installing-apache-thrift-on-mac-os-x-105-leopard/

The fastest way to build the compiler is:

$ svn co http://svn.apache.org/repos/asf/thrift/tags/thrift-0.7.0
$ cd thrift-0.7.0
$ cp /usr/X11/share/aclocal/pkg.m4 aclocal/
$ ./bootstrap.sh
$ ./configure
$ cd compiler/cpp/
$ make



***************************
*** Maven Thrift Plugin ***
***************************

A minimal configuration to invoke this plugin would be:

<project xmlns="http://maven.apache.org/POM/4.0.0"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <groupId>com.mycompany.example</groupId>
    <artifactId>example-thrift</artifactId>
    <packaging>jar</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>thrift-example</name>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.5</source>
                    <target>1.5</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.thrift.tools</groupId>
                <artifactId>maven-thrift-plugin</artifactId>
                <version>0.1.10</version>
                <configuration>
                    <thriftExecutable>/usr/local/bin/thrift</thriftExecutable>
                </configuration>
                <executions>
                    <execution>
                        <id>thrift-sources</id>
                        <phase>generate-sources</phase>
                        <goals>
                            <goal>compile</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>thrift-test-sources</id>
                        <phase>generate-test-sources</phase>
                        <goals>
                            <goal>testCompile</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>libthrift</artifactId>
            <version>0.5.0.0</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.5.8</version>
        </dependency>

        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.14</version>
        </dependency>
    </dependencies>
</project>


You must:
+ Use Java 1.5 or newer due to the usage of Generics
+ Either ensure the "thrift" executable is in your PATH or set the
  <thriftExecutable> parameter to the correct location.
+ Define the executions you want (you probably don't need the testCompile
  unless you have custom thrift objects in your tests.
+ Include the dependencies on libthrift and slf4j or your compile will fail.


Once this is all done add your *.thrift files to the directory: src/main/thrift

Everything should then build with a: mvn clean install




You may also need to add the following to your settings.xml to download the
plugin:

            <pluginRepositories>
                <pluginRepository>
                    <id>dtrott</id>
                    <url>http://maven.davidtrott.com/repository</url>
                </pluginRepository>
            </pluginRepositories>

  • 7
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
Maven插件是一种可插拔的工具,可以在Maven构建过程执行特定的任务。其maven-dependency-pluginmaven-surefire-plugin是两个常用的插件maven-dependency-plugin插件可以用来管理项目依赖,可以帮助我们列出项目的依赖关系,复制依赖文件到指定目录,解压依赖文件等。常用的配置包括: - list:列出项目依赖 - copy-dependencies:将所有依赖文件复制到指定目录 - unpack:解压指定的依赖文件 maven-surefire-plugin插件则是用来执行项目的单元测试的。它可以在Maven构建过程自动执行单元测试,并生成测试报告。常用的配置包括: - includes/excludes:指定要执行的测试类或排除的测试类 - parallel:指定测试是否并行执行 - reportsDirectory:指定测试报告生成的目录 在POM文件配置这两个插件,可以通过以下方式: ``` <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-dependency-plugin</artifactId> <version>3.2.0</version> <executions> <execution> <id>copy-dependencies</id> <phase>package</phase> <goals> <goal>copy-dependencies</goal> </goals> <configuration> <outputDirectory>${project.build.directory}/lib</outputDirectory> </configuration> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>3.0.0-M5</version> <configuration> <includes> <include>**/*Test.java</include> </includes> <parallel>methods</parallel> <threadCount>10</threadCount> <reportsDirectory>${project.build.directory}/surefire-reports</reportsDirectory> </configuration> </plugin> </plugins> </build> ``` 以上是一个简单的POM文件Maven插件配置maven-dependency-pluginmaven-surefire-plugin的示例,其maven-dependency-plugin在package阶段执行复制依赖文件的任务,maven-surefire-plugin在test阶段执行单元测试。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值