thrift java first demo

參考文檔:http://thrift.apache.org/java

1.下載須要的文件git

地址:http://thrift.apache.org/download  須要下載 github

2. 下載.thrift文件apache

  • shared.thrift: https://github.com/apache/thrift/blob/master/tutorial/shared.thrift  
  • tutorial.thrift: https://github.com/apache/thrift/blob/master/tutorial/tutorial.thrift

3. 生成.java文件ide

進入thrift-0.12.0.exe所在目錄,輸入命令:函數

thrift -r --gen java tutorial.thrift

產生文件夾 gen-Java文件夾,裏面包含兩個文件夾shared和tutorial。將文件夾移動至咱們工程的src/main/java目錄下。3d

4. 新建Maven工程,dependency裏增長code

<dependency>
  <groupId>org.apache.thrift</groupId>
  <artifactId>libthrift</artifactId>
  <version>0.12.0</version>
</dependency>

5. client & server & CalculatorHandlerserver

文件內容來自:http://thrift.apache.org/tutorial/javablog

將JavaClient.java和JavaServer.java放在src/main/java下。此時目錄結構以下:

6. 運行JavaServer的main函數

報錯:

 Starting the simple server...
 org.apache.thrift.transport.TTransportException: Error creating the transport
     at org.apache.thrift.transport.TSSLTransportFactory.createSSLContext(TSSLTransportFactory.java:)
     at org.apache.thrift.transport.TSSLTransportFactory.getServerSocket(TSSLTransportFactory.java:)
     at server.JavaServer.secure(JavaServer.java:)
     at server.JavaServer$.run(JavaServer.java:)
     at java.lang.Thread.run(Thread.java:)
 Caused by: java.io.IOException: Could not load file: ../../lib/java/test/.keystore
     at org.apache.thrift.transport.TSSLTransportFactory.getStoreAsStream(TSSLTransportFactory.java:)
     at org.apache.thrift.transport.TSSLTransportFactory.createSSLContext(TSSLTransportFactory.java:)
     ...  more

  緣由是secure模式須要有密鑰,代碼裏需將名爲.keystore的密鑰放在../../lib/java/test目錄下。若是使用simple模式,則不須要。因而,我修改了JavaServer.java代碼,將new Thread(secure).start(); 註釋掉了,再次啓動,未報錯。

7. 運行JavaClient的main函數

指明使用simple模式運行。

8. 運行結果

客戶端:

ping()
1+1=2
Invalid operation: Cannot divide by 0
15-10=5
Check log: 5

Process finished with exit code 0

服務端:

Starting the simple server...
ping()
add(1,1)
calculate(1, {DIVIDE,1,0})
calculate(1, {SUBTRACT,15,10})
getStruct(1)
相關文章
相關標籤/搜索