windows下在eclipse里面开发thrift的java的客户端和服务器

1.下载window下thrift的编译工具exe

        去apache官网(http://archive.apache.org/dist/thrift/)下载一个thrift的编译工具,我下载的是thrift-0.9.1.exe(最新版是thrift-0.9.1.exe),然后拷贝到E:\thrift下(位置自己随便放)

     (可以把E:\thrift加入到path下面去,重名名thrift-0.9.1.exe为thrift.exe  ,这样任何目录就可以使用thrift这个命令了,我并没有这么做)

 2. 编写thrift文件

     文件名为:demoHello.thrift     

namespace java com.kedacom.demo.thriftDemo
service  HelloWorldService {
    string sayHello(1:string username)
}

3. 编译thrift文件生成java文件

    打开windows下的命令行窗口,进入E:/thrift目录下面执行如下命令编译thrift文件

          thrift-0.9.1.exe --gen java demoHello.thrift

    162820_YMW2_1540325.png

     可以看到生成如下文件夹和文件:

   162959_kzWq_1540325.png

      可以看到生成了HelloWorldService.java文件了。

4. 在eclipse里面新建maven的java项目,引入libthrift-0.9.1.jar库,pom.xml内容如下

<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.kedacom.demo</groupId>
  <artifactId>thriftDemo</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>
  <name>thriftDemo</name>
  <url>http://maven.apache.org</url>
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
     <groupId>org.apache.thrift</groupId>
     <artifactId>libthrift</artifactId>
     <version>0.9.1</version>
        <exclusions>
          <exclusion>
             <groupId>org.slf4j</groupId>
             <artifactId>slf4j-log4j12</artifactId>
         </exclusion>
         <exclusion>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
         </exclusion>
         <exclusion>
           <groupId>log4j</groupId>
           <artifactId>log4j</artifactId>
         </exclusion>
      </exclusions>
   </dependency>
   <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>1.7.2</version>
    </dependency>
  </dependencies>
</project>

然后将我们刚才生成的HelloWorldService.java拷贝到我们的项目中

最后我们的目录结果如下:

164721_pLqA_1540325.png

5. 编写接口Iface实现代码

HelloWorldImpl.java:

package com.kedacom.demo.thriftDemo;
import org.apache.thrift.TException;
public class HelloWorldImpl implements HelloWorldService.Iface {
 
     public HelloWorldImpl() {
     }
    
     public String sayHello(String username) throws TException {
        // TODO Auto-generated method stub
        return "Hi," + username + " welcome to my blog www.micmiu.com";
     }
}

6. 编写server代码

       HelloServerDemo:

package com.kedacom.demo.thriftDemo;
import org.apache.thrift.TProcessor;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TCompactProtocol;
import org.apache.thrift.protocol.TJSONProtocol;
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 ....");
 
            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());
            // tArgs.protocolFactory(new TCompactProtocol.Factory());
            // tArgs.protocolFactory(new TJSONProtocol.Factory());
            TServer server = new TSimpleServer(tArgs);
            server.serve();
        } catch (Exception e) {
            System.out.println("Server start error!!!");
            e.printStackTrace();
        }
    }
 
    public static void main(String[] args) {
        HelloServerDemo server = new HelloServerDemo();
        server.startServer();
    }
}

7.编写client代码
       HelloClientDemo.java代码

package com.kedacom.demo.thriftDemo;
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;
 
 
     public void startClient(String userName) {
        TTransport transport = null;
        try {
             transport = new TSocket(SERVER_IP, SERVER_PORT, TIMEOUT);
             // 协议要和服务端一致
             TProtocol protocol = new TBinaryProtocol(transport);
             // TProtocol protocol = new TCompactProtocol(transport);
             // TProtocol protocol = new TJSONProtocol(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();
             }
         }
     }  
 

  public static void main(String[] args) {
         HelloClientDemo client = new HelloClientDemo();
         client.startClient("Michael"); 
  }
}

8.先运行server端,控制台输出如下

171309_YD4M_1540325.png

9再运行client端,控制台输出如下:

171356_GkX4_1540325.png

至此客户端调用服务器的函数成功。

转载于:https://my.oschina.net/u/1540325/blog/549136

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的 Thrift 示例,包含服务器客户端,使用 C++ 编写。 1. 首先,我们需要定义一个 Thrift IDL 文件。在这个例子中,我们定义了一个简单的服务,可以将两个整数相加并返回结果。在一个名为 "math.thrift" 的文件中,我们写下以下代码: ``` namespace cpp tutorial service Calculator { i32 add(1:i32 num1, 2:i32 num2) } ``` 2. 接下来,我们需要使用 Thrift 编译器生成 C++ 代码。在终端中运行以下命令: ``` thrift --gen cpp math.thrift ``` 这将生成一个 "gen-cpp" 文件夹,其中包含 Thrift 自动生成的 C++ 代码。 3. 现在,我们可以着手编写服务器端代码。在一个名为 "server.cpp" 的文件中,我们编写以下代码: ```cpp #include <iostream> #include <thrift/protocol/TBinaryProtocol.h> #include <thrift/server/TSimpleServer.h> #include <thrift/transport/TServerSocket.h> #include <thrift/transport/TBufferTransports.h> #include "gen-cpp/Calculator.h" using namespace std; using namespace apache::thrift; using namespace apache::thrift::protocol; using namespace apache::thrift::transport; using namespace apache::thrift::server; using namespace cpp_tutorial; class CalculatorHandler : public CalculatorIf { public: CalculatorHandler() {} int32_t add(const int32_t num1, const int32_t num2) { cout << "Adding " << num1 << " and " << num2 << endl; return num1 + num2; } }; int main(int argc, char** argv) { int port = 9090; shared_ptr<CalculatorHandler> handler(new CalculatorHandler()); shared_ptr<TProcessor> processor(new CalculatorProcessor(handler)); shared_ptr<TServerTransport> serverTransport(new TServerSocket(port)); shared_ptr<TTransportFactory> transportFactory(new TBufferedTransportFactory()); shared_ptr<TProtocolFactory> protocolFactory(new TBinaryProtocolFactory()); TSimpleServer server(processor, serverTransport, transportFactory, protocolFactory); cout << "Starting the server..." << endl; server.serve(); cout << "Done." << endl; return 0; } ``` 这个代码片段创建了一个 `CalculatorHandler` 类,它实现了 "add" 方法,将两个整数相加并返回结果。然后,我们创建一个 `CalculatorProcessor` 对象来处理客户端请求,并使用 `TSimpleServer` 类来启动服务器。 4. 最后,我们需要编写客户端代码。在一个名为 "client.cpp" 的文件中,我们编写以下代码: ```cpp #include <iostream> #include <thrift/transport/TBufferTransports.h> #include <thrift/protocol/TBinaryProtocol.h> #include <thrift/transport/TSocket.h> #include "gen-cpp/Calculator.h" using namespace std; using namespace apache::thrift; using namespace apache::thrift::protocol; using namespace apache::thrift::transport; using namespace cpp_tutorial; int main(int argc, char** argv) { shared_ptr<TTransport> socket(new TSocket("localhost", 9090)); shared_ptr<TTransport> transport(new TBufferedTransport(socket)); shared_ptr<TProtocol> protocol(new TBinaryProtocol(transport)); CalculatorClient client(protocol); try { transport->open(); int32_t num1 = 3; int32_t num2 = 5; int32_t sum = client.add(num1, num2); cout << "Sum of " << num1 << " and " << num2 << " is: " << sum << endl; transport->close(); } catch (TException& e) { cerr << "Error: " << e.what() << endl; } return 0; } ``` 这个代码片段创建了一个 `TSocket` 对象,用于连接到服务器的地址和端口。然后,我们使用 `TBufferedTransport` 和 `TBinaryProtocol` 对象创建 `CalculatorClient` 对象,并调用 `add` 方法。最后,我们关闭传输并打印出结果。 5. 最后,我们可以编译并运行服务器客户端。在终端中分别运行以下命令: ``` g++ -std=c++11 -o server server.cpp gen-cpp/*.cpp -lthrift ``` ``` g++ -std=c++11 -o client client.cpp gen-cpp/*.cpp -lthrift ``` 然后,首先运行服务器: ``` ./server ``` 接下来,运行客户端: ``` ./client ``` 输出应该会类似于以下内容: ``` Starting the server... Adding 3 and 5 Done. Sum of 3 and 5 is: 8 ``` 这表明服务器已经启动,并且客户端能够成功调用服务器的方法并接收返回值。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值