Java实现Thrift实例

该文详细介绍了如何使用Java实现Thrift服务,包括编写.thrift文件定义服务,配置maven-thrift-plugin插件生成源码,创建服务端实现类并启动服务,以及客户端调用服务的方法。同时,展示了多模块项目的结构和相关POM配置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Java实现Thrift实例

前提

需要先下载编译器http://archive.apache.org/dist/thrift/,分为Linux版和Windows,具体编译器的版本跟thriftlib包的版本是相同配套的。

选择使用的是thrift-0.17.0版本

JDK1.8

步骤说明

  1. 编写.thrift文件确认服务功能

    定义命名空间,即语言和生成的源码文件的位置

    // 定义命名空间,即语言和生成的源码文件的位置
    namespace java com.donny.thrift.service
    // 定义服务,即源码文件类名
    service  HelloService {
      // 定义一个无返回的方法
      void report(1:string data)
      // 一个有返回的方法
    }
    
  2. 从thrift文件构建源代码

    利用maven-thrift-plugin插件进行操作。POM文件的相关配置

    注意:<outputDirectory>在执行源码生成会清空目录下原来的所有文件和文件夹

                <plugin>
                    <groupId>org.apache.thrift.tools</groupId>
                    <artifactId>maven-thrift-plugin</artifactId>
                    <version>0.1.11</version>
                    <configuration>
                        <!-- 指的是thrift编译器的位置,如果我们配置了环境变量,可以不指定。-->
                        <thriftExecutable>${basedir}/src/main/resources/thrift/thrift-${thrift.version}.exe</thriftExecutable>
                        <!-- .thrift源文件的目录,默认会从src/main/thrift下读取。-->
                        <thriftSourceRoot>${basedir}/src/main/resources/thrift</thriftSourceRoot>
                        <!-- 高版本之后需要指明generator为java-->
                        <generator>java</generator>
                        <!--这个目录是生成的源码输入路径,注意,会清空目录下原来的所有文件和文件夹-->
                        <!-- <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>
    

    mvn clean install 或者通过IDEA的图形界面上点击按钮。

    将生成的文件copy至项目工程源码文件夹中。

  3. 编写服务端

    编写服务实现类,实现具体的功能。

    public class HelloServiceImpl implements HelloService.Iface

    编写服务端的启动类

         try {
                System.out.println("服务端开启....");
                // 声明一个HelloService的处理器,绑定接口和实现类
                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();
            }
    
  4. 编写客户端

    测试服务端的功能

        public static void main(String[] args) {
            System.out.println("客户端启动....");
            try (TTransport transport = new TSocket("localhost", 50005)) {
                TProtocol protocol = new TBinaryProtocol(transport);
                HelloService.Client client = new HelloService.Client(protocol);
                // 打开传输
                transport.open();
                // 客户端调用
                String ping = client.ping("活着吗");
                if ("active".equals(ping)) {
                    System.out.println("服务端正常!");
                    client.report("我来了 我是消息");
                }
    
                System.out.println("结束");
            } catch (TException e) {
                e.printStackTrace();
            }
        }
    
  5. 先启动服务启动类,在执行Client的main。

    客户端打印

    客户端启动....
    服务端正常!
    结束
    

    服务端打印

    服务端开启....
    接收数据:我来了 我是消息
    

采用多模块方式开发的,完整的pom文件。

根模块pom.xml

<?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.donny</groupId>
    <artifactId>ThriftJava</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>
    <modules>
        <module>server</module>
        <module>client</module>
    </modules>

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

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>3.6.0</version>
            </plugin>
        </plugins>
    </build>
</project>

服务端pom.xml

<?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">
    <parent>
        <artifactId>ThriftJava</artifactId>
        <groupId>com.donny</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>server</artifactId>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <thrift.version>0.17.0</thrift.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.apache.thrift</groupId>
            <artifactId>libthrift</artifactId>
            <version>${thrift.version}</version>
        </dependency>

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

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-nop</artifactId>
            <version>2.0.7</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.thrift.tools</groupId>
                <artifactId>maven-thrift-plugin</artifactId>
                <version>0.1.11</version>
                <configuration>
                    <!-- 指的是thrift编译器的位置,如果我们配置了环境变量,可以不指定。-->
                    <thriftExecutable>${basedir}/src/main/resources/thrift/thrift-${thrift.version}.exe
                    </thriftExecutable>
                    <!-- .thrift源文件的目录,默认会从src/main/thrift下读取。-->
                    <thriftSourceRoot>${basedir}/src/main/resources/thrift</thriftSourceRoot>
                    <!-- 高版本之后需要指明generator为java-->
                    <generator>java</generator>
                    <!--这个目录是生成的源码输入路径,注意,会清空目录下原来的所有文件和文件夹-->
                    <!-- <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>

类文件HelloServiceImpl.java

package com.donny.thrift.service;

import org.apache.thrift.TException;

/**
 * 服务的实现类,需要将服务中定义的功能进行具体的实现
 *
 */
public class HelloServiceImpl implements HelloService.Iface {
    @Override
    public void report(String data) throws TException {
        System.out.println("接收数据:" + data);
    }

    @Override
    public String ping(String data) throws TException {
        return "active";
    }
}

客户端pom.xml

<?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">
    <parent>
        <artifactId>ThriftJava</artifactId>
        <groupId>com.donny</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>client</artifactId>

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

    <dependencies>
        <dependency>
            <groupId>com.donny</groupId>
            <artifactId>server</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
    </dependencies>
</project>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

顧棟

若对你有帮助,望对作者鼓励一下

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值