Getting Started with Thrift: Implement RPC in Java

This article introduces Apache Thrift, explains its cross‑language IDL, data types, transport and protocol options, and walks through setting up the Thrift compiler, adding a Gradle dependency, writing a .thrift definition, generating Java code, and building a simple Java RPC server and client.

The Dominant Programmer
The Dominant Programmer
The Dominant Programmer
Getting Started with Thrift: Implement RPC in Java

Thrift, originally developed by Facebook, is an IDL‑based RPC framework that enables services written in different languages (C++, Java, Python, etc.) to communicate through generated code and a common protocol.

Supported primitive types include byte, i16, i32, i64, double, and string. Containers such as list, set, and map are also provided, and complex structures can be defined with struct, enum, and exception. Fields may be marked required or optional.

Thrift separates the transport layer ( TSocket, TFramedTransport, TFileTransport, TMemoryTransport, TZlibTransport) from the protocol layer ( TBinaryProtocol, TCompactProtocol, TJSONProtocol, TSimpleJSONProtocol, TDebugProtocol). Server models include TSimpleServer, TThreadPoolServer, and TNonblockingServer.

On Windows, download the Thrift compiler (e.g., thrift-0.13.0.exe) from http://thrift.apache.org/download, place it in a directory, add that directory to the system PATH, and verify with thrift -version.

In a Gradle project, add the Thrift library:

dependencies {
    compile group: 'org.apache.thrift', name: 'libthrift', version: '0.13.0'
}

Create src/thrift/MyData.thrift:

namespace java thrift.generated

typedef i16 short

typedef i32 int

typedef i64 long

typedef bool boolean

typedef string String

struct Person {
    1: optional String username,
    2: optional int age,
    3: optional boolean married
}

exception DataException {
    1: optional String message,
    2: optional String callback,
    3: optional String date
}

service PersonService {
    Person getPersonByUsername(1: required String username) throws (1: DataException dataException),
    void savePerson(1: required Person person) throws (1: DataException dataException)
}

Generate Java code with: thrift --gen java src/thrift/MyData.thrift Place the generated sources under src/main/java/com/badao/thrift.

Implement the service:

package com.badao.Thrift;

import org.apache.thrift.TException;

public class PersonServiceImpl implements PersonService.Iface {
    @Override
    public Person getPersonByUsername(String username) throws DataException, TException {
        System.out.println("getPersonByUsername called with: " + username);
        Person p = new Person();
        p.setUsername("公众号:霸道的程序猿");
        p.setAge(100);
        p.setMarried(true);
        return p;
    }

    @Override
    public void savePerson(Person person) throws DataException, TException {
        System.out.println("savePerson called with:");
        System.out.println(person.getUsername());
        System.out.println(person.getAge());
        System.out.println(person.isMarried());
    }
}

Start a non‑blocking server:

package com.badao.Thrift;

import org.apache.thrift.TProcessorFactory;
import org.apache.thrift.protocol.TCompactProtocol;
import org.apache.thrift.server.THsHaServer;
import org.apache.thrift.server.TServer;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TNonblockingServerSocket;

public class ThriftServer {
    public static void main(String[] args) throws Exception {
        TNonblockingServerSocket serverSocket = new TNonblockingServerSocket(8899);
        THsHaServer.Args arg = new THsHaServer.Args(serverSocket)
                .minWorkerThreads(2).maxWorkerThreads(4);
        PersonService.Processor<PersonServiceImpl> processor =
                new PersonService.Processor<>(new PersonServiceImpl());
        arg.protocolFactory(new TCompactProtocol.Factory());
        arg.transportFactory(new TFramedTransport.Factory());
        arg.processorFactory(new TProcessorFactory(processor));
        TServer server = new THsHaServer(arg);
        System.out.println("Thrift server started");
        server.serve();
    }
}

Create a client to invoke the service:

package com.badao.Thrift;

import org.apache.thrift.protocol.TCompactProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;

public class ThriftClient {
    public static void main(String[] args) {
        TTransport transport = new TFramedTransport(new TSocket("localhost", 8899), 600);
        TProtocol protocol = new TCompactProtocol(transport);
        PersonService.Client client = new PersonService.Client(protocol);
        try {
            transport.open();
            Person p = client.getPersonByUsername("公众号:霸道的程序猿");
            System.out.println(p.getUsername());
            System.out.println(p.getAge());
            System.out.println(p.isMarried());
            System.out.println("------------------------");
            Person p2 = new Person();
            p2.setUsername("公众号:霸道的程序猿");
            p2.setAge(50);
            p2.setMarried(true);
            client.savePerson(p2);
        } catch (Exception ex) {
            throw new RuntimeException(ex.getMessage(), ex);
        } finally {
            transport.close();
        }
    }
}

Run ThriftServer first, then execute ThriftClient. The client prints the retrieved Person fields and confirms that the savePerson method was invoked on the server.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaRPCGradleCross-languageIDLApache ThriftThrift
The Dominant Programmer
Written by

The Dominant Programmer

Resources and tutorials for programmers' advanced learning journey. Advanced tracks in Java, Python, and C#. Blog: https://blog.csdn.net/badao_liumang_qizhi

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.