【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。目录结构如下:

【maven】maven-thrift-plugin 插件使用 + Java项目中thrift使用的正确姿势_第1张图片

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

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

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

所以maven的pom文件如下:




  4.0.0

  com.liyao
  thrift_plugin_project
  1.0-SNAPSHOT

  thrift_project
  
  http://www.example.com

  
    UTF-8
    1.7
    1.7
  

  
    
    
      org.apache.thrift
      libthrift
      0.9.3
    
  

  
      
          
              org.apache.thrift.tools
              maven-thrift-plugin
              0.1.11
              
                  
                  
                  
              
              
                  
                      thrift-sources
                      generate-sources
                      
                          compile
                      
                  
                  
                      
                      
                      
                          
                      
                  
              
          
      
  

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

【maven】maven-thrift-plugin 插件使用 + Java项目中thrift使用的正确姿势_第2张图片

【maven】maven-thrift-plugin 插件使用 + Java项目中thrift使用的正确姿势_第3张图片

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


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

pom:




    4.0.0

    com.liyao
    thrift_project
    1.0-SNAPSHOT

    thrift_project
    
    http://www.example.com

    
        UTF-8
        1.7
        1.7
    

    
        
            junit
            junit
            4.11
            test
        

        
            com.liyao
            thrift_plugin_project
            1.0-SNAPSHOT
        

        
        
            org.apache.thrift
            libthrift
            0.9.3
        
    

服务实现类:

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(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:

        
            org.apache.thrift
            libthrift
            0.7.0
        


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:



    4.0.0
    com.mycompany.example
    example-thrift
    jar
    1.0-SNAPSHOT
    thrift-example

    
        
            
                org.apache.maven.plugins
                maven-compiler-plugin
                
                    1.5
                    1.5
                
            
            
                org.apache.thrift.tools
                maven-thrift-plugin
                0.1.10
                
                    /usr/local/bin/thrift
                
                
                    
                        thrift-sources
                        generate-sources
                        
                            compile
                        
                    
                    
                        thrift-test-sources
                        generate-test-sources
                        
                            testCompile
                        
                    
                
            
        
    

    
        
            org.apache.hadoop
            libthrift
            0.5.0.0
        

        
            org.slf4j
            slf4j-api
            1.5.8
        

        
            log4j
            log4j
            1.2.14
        
    



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
   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:

            
                
                    dtrott
                    http://maven.davidtrott.com/repository
                
            

你可能感兴趣的:(maven)