java中thrift 入門詳解

來源:互聯網
上載者:User


install

brew install thrift

例子

maven

<dependencies>
    <dependency>
        <groupId>org.apache.thrift</groupId>
        <artifactId>libthrift</artifactId>
        <version>0.9.3</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.5.8</version>
    </dependency>
</dependencies>
IDL

編寫thrift IDL檔案hello.thrift,用於產生java代碼

namespace java demo

service HelloService {
    string hi()
}
generate

執行名聲,產生java代碼

thrift -gen java hello.thrift

此時,會在目前的目錄下產生java-gen檔案夾,其中包含所需要的thrift介面檔案HelloService.java.

impl

上步中產生了相應的HelloServie.Iface介面,所以需要實現該介面檔案,


package demo;

public class HelloImpl implements HelloService.Iface {
    public String hi() {
        return "Hi!!!";
    }
}

server

package demo;

import org.apache.thrift.server.TServer;
import org.apache.thrift.server.TSimpleServer;
import org.apache.thrift.transport.TServerSocket;
import org.apache.thrift.transport.TServerTransport;

public class Server {
    public static void main(String[] args) {
        HelloImpl hello = new HelloImpl();
        final HelloService.Processor<HelloImpl> p =
                new HelloService.Processor<HelloImpl>(hello);

        new Thread(new Runnable() {
            public void run() {
                try {
                    TServerTransport st = new TServerSocket(9000);
                    TServer tServer = new TSimpleServer(new TServer.Args(st).processor(p));
                    System.out.println("Starting ...");
                    tServer.serve();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}

client

注意server使用的連接埠9000,


package demo;

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;

public class Client {
    public static void main(String[] args) throws TException {
        TTransport ts = new TSocket("localhost", 9000);
        ts.open();

        TProtocol p = new TBinaryProtocol(ts);
        HelloService.Client client = new HelloService.Client(p);

        System.out.println(client.hi());

        ts.close();
    }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.