欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Thrift 入门Demo Java版本

程序员文章站 2022-06-17 12:00:55
...

1.创建thrift文件

新建一个maven项目,定义一个羡慕首先定义一个thrift文件,位置随意

service  HelloWorldService {
  string sayHello(1:string username)
}

这就定义好了一个名字为 HelloWorldService 的服务,后续客户端和服务端代码都是围绕这个HelloWorldService来写的

2.生成thrift代码

切到HelloWorldService.thrift文件所在的跟目录下,在命令行执行H

thrift  -gen java HelloWorldService.thrift

java 表示要生成的是java代码,还可以生成python,c,c++等

Thrift 入门Demo Java版本

以下为HelloWorldService.java的部分代码,主要是Iface和client

 public interface Iface {

    public String sayHello(String username) throws org.apache.thrift.TException;

  }

  public static class Client extends org.apache.thrift.TServiceClient implements Iface {
    public static class Factory implements org.apache.thrift.TServiceClientFactory<Client> {
      public Factory() {}
      public Client getClient(org.apache.thrift.protocol.TProtocol prot) {
        return new Client(prot);
      }
      public Client getClient(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) {
        return new Client(iprot, oprot);
      }
    }

    public Client(org.apache.thrift.protocol.TProtocol prot)
    {
      super(prot, prot);
    }

    public Client(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) {
      super(iprot, oprot);
    }

    public String sayHello(String username) throws org.apache.thrift.TException
    {
      send_sayHello(username);
      return recv_sayHello();
    }

    public void send_sayHello(String username) throws org.apache.thrift.TException
    {
      sayHello_args args = new sayHello_args();
      args.setUsername(username);
      sendBase("sayHello", args);
    }

    public String recv_sayHello() throws org.apache.thrift.TException
    {
      sayHello_result result = new sayHello_result();
      receiveBase(result, "sayHello");
      if (result.isSetSuccess()) {
        return result.success;
      }
      throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "sayHello failed: unknown result");
    }

  }

Iface是个接口文件,主要是用来被服务器端的程序继承和重写的,Iface里面定义了方法的接口,在服务器端的程序中应当实现这个接口,而client程序中定义了sayHello 方法,而sayHello 方法中又调用了send_sayHellorecv_hello 用来发送请求和接受反馈,具体通信的细节不用用户去考虑,thrift已经帮我们完全生成好了,只需要我们具体实现sayhello的方法

3.实现接口

可以新建一个包,名为common,里面存client 和server都会用到的代码,新建HelloWorldImpl 文件用来实现之前生成的接口,这里重写了sayHello方法

package common;

public class HelloWorldImpl implements  HelloWorldService.Iface {
    public  HelloWorldImpl(){
    }
    @Override
    public  String sayHello(String username){
        return "hi " + username +"welcome to thrift world";
    }
}

4.服务端代码

新建 HelloServerDemo java

package server;


import common.HelloWorldImpl;
import common.HelloWorldService;
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;

public class HelloServerDemo {
    public  static  final int  SERVER_PORT = 8090;
    public void startServer() {
        try {
            System.out.println("HelloWorld TSimpleServer start ....");

            //在这里调用了 HelloWorldImpl 规定了接受的方法和返回的参数
            TProcessor tprocessor = new HelloWorldService.Processor<HelloWorldService.Iface>( new HelloWorldImpl());

            TServerSocket serverTransport = new TServerSocket(SERVER_PORT);
            TServer.Args tArgs = new TServer.Args(serverTransport);
            tArgs.processor(tprocessor);
            tArgs.protocolFactory(new TBinaryProtocol.Factory());

            TServer server = new TSimpleServer(tArgs);
            server.serve();

        } catch (Exception e) {
            System.out.println("Server start error!!!");
            e.printStackTrace();
        }
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        HelloServerDemo server = new HelloServerDemo();
        server.startServer();
    }

}

5.客户端代码

package client;

import common.HelloWorldService;
import org.apache.hadoop.yarn.webapp.example.HelloWorld;
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 HelloClientDemo {

    public static final String SERVER_IP = "localhost";
    public static final int SERVER_PORT = 8090;
    public static final int TIMEOUT = 30000;

    /**
     *
     * @param userName
     */
    public void startClient(String userName) {
        TTransport transport = null;
        try {
            transport = new TSocket(SERVER_IP, SERVER_PORT, TIMEOUT);
            // 协议要和服务端一致
            TProtocol protocol = new TBinaryProtocol(transport);

            HelloWorldService.Client client = new HelloWorldService.Client(protocol);
            transport.open();
            String result = client.sayHello(userName);
            System.out.println("Thrify client result =: " + result);
        } catch (TTransportException e) {
            e.printStackTrace();
        } catch (TException e) {
            e.printStackTrace();
        } finally {
            if (null != transport) {
                transport.close();
            }
        }
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        HelloClientDemo client = new HelloClientDemo();
        client.startClient("china");

    }

}

调用HelloWorldService的client即可,client可以调用sayHello方法,向服务器传递参数,并接受服务器返回的信息

6.小结

首先生成了HelloWorldService文件,然后通过HelloWorldImpl实现了HelloWorldService的Iface接口,这个包impl文件只会在服务器端被调用,来规定服务器端返回的信心,而客户端程序只需要调用HelloWorldService中的client
项目目录结构如下
Thrift 入门Demo Java版本

相关标签: Thrift