Java使用Thrift,Thrift結構體定義


1、Thrift定義文件,Thrift常見的數據類型

1.基本類型(括號內為對應的Java類型):
bool(boolean): 布爾類型(TRUE or FALSE)
bytebyte): 8位帶符號整數
i16(short): 16位帶符號整數
i32(int): 32位帶符號整數
i64(long): 64位帶符號整數
doubledouble): 64位浮點數
string(String): 采用UTF-8編碼的字符串
2.特殊類型(括號內為對應的Java類型):
    binary(ByteBuffer):未經過編碼的字節流
3.Structs(結構===JAVA(對象))
4.容器 Thrift提供了3種容器類型:
List<Object>:一系列t1類型的元素組成的有序表,元素可以重復
Set<Object>:一系列t1類型的元素組成的無序表,元素唯一
Map<Object,Object>:key/value對(key的類型是t1且key唯一,value類型是t2)。
    容器中的元素類型可以是除了service意外的任何合法thrift類型(包括結構體和異常)。
5.其他**
    namespace 相當於java創建包 java com.thrift.membersheep.server 說明創建java 的包
    service 相當於java 創建Class

2、Thrift簡單結構體demo,寫好了過后保存文件名后綴已.thrift結尾,如(ETH_CORE.thrift)

namespace java com.thrift.eth
//交易所_創建eth賬號 struct EXCHANGE_CREATE_ETH_ACCOUNT_MODEL{ 1: string path, //賬號存放地址 2: string password,//密碼 3: string phone_filename//賬號名稱 } //交易所_返回創建eth賬號信息 struct EXCHANGE_RETURN_ETH_ACCOUNT{ 1: string address;//賬號地址 2: string privateKey;//私鑰 3: string publicKey;//公鑰 4: string password;//密碼 5: double coinQuantity;//貨幣數量 6: string message;//消息 7: i32 status;//狀態 } //交易所_轉賬eth struct EXCHANGE_TRANSFER_ETH_MODEL{ 1: string https_web3j,//web3j url 2: string path_file,//賬號文件路徑 3: string address,//賬號地址 4: string password,//密碼 5: string to_address,//轉到那個賬號地址 6: double quantity//轉賬數量 } //交易所_返回轉賬信息 struct EXCHANGE_RETURN_TRANSFER{ 1: string message;//消息 2: i32 status;//狀態 } //交易所_轉賬sheep struct EXCHANGE_TRANSFER_SHEEP_MODEL{ 1: string https_web3j,//web3j url 2: string path_file,//賬號文件路徑 3: string address,//賬號地址 4: string password,//密碼 5: string to_address,//轉到那個賬號地址 6: double quantity,//轉賬數量 7: string contract_address//合約地址 } service ETH_CORE{//===========================================exhagne eth相關操作 //創建eth賬號 EXCHANGE_RETURN_ETH_ACCOUNT create_eth_address(1:EXCHANGE_CREATE_ETH_ACCOUNT_MODEL create_eth_model) //eth轉賬 EXCHANGE_RETURN_TRANSFER transfer_eth(1:EXCHANGE_TRANSFER_ETH_MODEL transfer_eth_model) //獲取eth余額 double get_eth_balance(1:string https_web3j,2:string address) //sheep轉賬 EXCHANGE_RETURN_TRANSFER transfer_sheep(1:EXCHANGE_TRANSFER_SHEEP_MODEL transfer_sheep_model) //獲取sheep余額 double get_sheep_balance(1:string https_web3j,2:string address,3:string contract_address) }

3、下載客服端http://thrift.apache.org/download,

4、反編譯成java文件(windows版),把寫好的thrift結構體放到與客服端同級

 然后點擊地址欄輸入cmd回車運行

 反編譯成java命令:thrift-0.10.0 -gen java ETH_CORE.thrift 如:

回車過后文件夾下面就會自動生成java文件

 

然后點擊去看java文件就生成好了

然后到java端使用

 1、maven jar使用

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

2、先把核心包使用,就是開始創建的結構體,單獨作用於一個項目,當做jar使用

3、服務器使用 pom.xml也是要引用ThriftCore項目

<dependency>
   <groupId>com.lpizi</groupId>
   <artifactId>ThriftCore</artifactId>
    <version>1.0-SNAPSHOT</version>
    <exclusions>
        <exclusion>
            <groupId>jline</groupId>
             <artifactId>jline</artifactId>
         </exclusion>
    </exclusions>
</dependency>

 

3.1、ThriftServer類

package com.thrift.server;


import com.thrift.eth.ETH_CORE;
import com.thrift.web3j.DefaultEth;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.server.TServer;
import org.apache.thrift.server.TSimpleServer;
import org.apache.thrift.transport.TServerSocket;
import org.apache.thrift.transport.TTransportException;

public class ThriftServer {public static void main(String[] args){
        try {
            // 設置服務器端口
            TServerSocket serverTransport = new TServerSocket(端口);
            // 設置二進制協議工廠
            TBinaryProtocol.Factory protocolFactory = new TBinaryProtocol.Factory();
            // 處理器關聯業務實現
            ETH_CORE.Processor<ETH_CORE.Iface> processor = new ETH_CORE.Processor<ETH_CORE.Iface>((ETH_CORE.Iface) new EthServiceImpl());
            //使用單線程標准阻塞I/O模型
            TServer.Args simpleArgs = new TServer.Args(serverTransport)
                    .processor(processor)
                    .protocolFactory(protocolFactory);
            TServer server = new TSimpleServer(simpleArgs);
            System.out.println("=====>開啟thrift服務器,監聽端口:"+DefaultEth.ThrifProp+"<=================");
            server.serve();
        } catch (TTransportException e) {
            e.printStackTrace();
        }
    }

}

3.2、EthServiceImpl類

package com.thrift.server;

import com.alibaba.fastjson.JSON;
import com.membersheep.ethereum.model.ConfirmModel;
import com.membersheep.ethereum.model.OrderDetailModel;
import com.membersheep.ethereum.model.exchange.AccountModel;
import com.membersheep.ethereum.model.exchange.TransferModel;
import com.membersheep.ethereum.web3j.TransctionContract;
import com.membersheep.ethereum.web3j.exchange.EthAccount;
import com.thrift.eth.*;
import org.apache.thrift.TException;

import java.util.ArrayList;
import java.util.List;

public class EthServiceImpl implements ETH_CORE.Iface {
    private EthAccount ethAccount=new EthAccount();
  /*
   注意方法里面的內容是根據你自己的需求來操作,我這里是操作eth相關的 
  */
/** * 創建ETH賬號 * @param create_eth_model * @return * @throws TException */ @Override public EXCHANGE_RETURN_ETH_ACCOUNT create_eth_address(EXCHANGE_CREATE_ETH_ACCOUNT_MODEL create_eth_model) throws TException { EXCHANGE_RETURN_ETH_ACCOUNT returnEthAccount=new EXCHANGE_RETURN_ETH_ACCOUNT(); AccountModel accountModel=ethAccount.create(create_eth_model.path,create_eth_model.password,create_eth_model.phone_filename); returnEthAccount.address=accountModel.address; returnEthAccount.coinQuantity=accountModel.coinQuantity; returnEthAccount.message=accountModel.message; returnEthAccount.password=accountModel.password; returnEthAccount.privateKey=accountModel.privateKey; returnEthAccount.publicKey=accountModel.publicKey; returnEthAccount.status=accountModel.status; return returnEthAccount; } /** * eth轉賬 * @param transfer_eth_model * @return * @throws TException */ @Override public EXCHANGE_RETURN_TRANSFER transfer_eth(EXCHANGE_TRANSFER_ETH_MODEL transfer_eth_model) throws TException { EXCHANGE_RETURN_TRANSFER returnTransfer=new EXCHANGE_RETURN_TRANSFER(); TransferModel transferModel=ethAccount.transferETH(transfer_eth_model.https_web3j,transfer_eth_model.path_file,transfer_eth_model.address,transfer_eth_model.password,transfer_eth_model.to_address,transfer_eth_model.quantity); returnTransfer.message=transferModel.message; returnTransfer.status=transferModel.status; return returnTransfer; } /** * 獲取eth余額 * @param https_web3j * @param address * @return * @throws TException */ @Override public double get_eth_balance(String https_web3j, String address) throws TException { return ethAccount.getETHBalance(https_web3j,address); } /** * sheep轉賬 * @param transfer_sheep_model * @return * @throws TException */ @Override public EXCHANGE_RETURN_TRANSFER transfer_sheep(EXCHANGE_TRANSFER_SHEEP_MODEL transfer_sheep_model) throws TException { EXCHANGE_RETURN_TRANSFER returnTransfer=new EXCHANGE_RETURN_TRANSFER(); TransferModel transferModel=ethAccount.transferSHEEP(transfer_sheep_model.https_web3j,transfer_sheep_model.path_file, transfer_sheep_model.address,transfer_sheep_model.password,transfer_sheep_model.to_address, transfer_sheep_model.quantity,transfer_sheep_model.contract_address); returnTransfer.message=transferModel.message; returnTransfer.status=transferModel.status; return returnTransfer; } /** * 獲取sheep余額 * @param https_web3j * @param address * @param contract_address * @return * @throws TException */ @Override public double get_sheep_balance(String https_web3j, String address, String contract_address) throws TException { return ethAccount.getSHEEPBalance(https_web3j,address,contract_address); } }

end 這上面服務端就好了

4、客戶端使用pom.xml也是要引用ThriftCore項目(同服務端調用)如下這個兩個類就OK了

4.1、GetServer類

package com.membersheep.util.thrift;

import com.membersheep.util.proper.DefaultProp;
import com.thrift.eth.ETH_CORE;
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 GetServer {
    /**
     * 獲取通訊鏈接
     * @return
     */
    public TTransport get_transport(){
        // 設置調用的服務地址-端口
        return new TSocket(服務端URL, 服務端端口);
    }

    /**
     * 打開通道
     * @return
     * @throws TTransportException
     */
    public ETH_CORE.Client open_client(TTransport transport) throws TTransportException {
        // 使用二進制協議
        TProtocol protocol = new TBinaryProtocol(transport);
        // 使用的接口
        ETH_CORE.Client client = new ETH_CORE.Client(protocol);
        // 打開socket
        transport.open();
        return client;
    }
}

4.2、ThriftExchangeEthClient類,還是那句話方法里面的東西根據自己的需求定義

package com.membersheep.util.thrift;


import com.thrift.eth.*;
import org.apache.thrift.TException;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class ThriftExchangeEthClient {
    private static Logger logger= LoggerFactory.getLogger(ThriftExchangeEthClient.class);

    /**
     * 創建eth賬號
     * @param create_eth_account_model
     * @return
     */
    public EXCHANGE_RETURN_ETH_ACCOUNT create_eth_address(EXCHANGE_CREATE_ETH_ACCOUNT_MODEL create_eth_account_model){
        EXCHANGE_RETURN_ETH_ACCOUNT returnEthAccount=new EXCHANGE_RETURN_ETH_ACCOUNT();
        GetServer getServer=new GetServer();
        TTransport transport=getServer.get_transport();
        try {
            ETH_CORE.Client client = getServer.open_client(transport);
            returnEthAccount=client.create_eth_address(create_eth_account_model);
        } catch (TTransportException e) {
            logger.error("create_eth_address==>TTransportException====>"+e.getMessage());
        } catch (TException e) {
            logger.error("create_eth_address==>TException====>"+e.getMessage());
        }finally {
            transport.close();
        }
        return returnEthAccount;
    }

    /**
     * eth轉賬
     * @param transfer_eth_model
     * @return
     */
    public EXCHANGE_RETURN_TRANSFER transfer_eth(EXCHANGE_TRANSFER_ETH_MODEL transfer_eth_model){
        EXCHANGE_RETURN_TRANSFER returnTransfer=new EXCHANGE_RETURN_TRANSFER();
        GetServer getServer=new GetServer();
        TTransport transport=getServer.get_transport();
        try {
            ETH_CORE.Client client = getServer.open_client(transport);
            returnTransfer=client.transfer_eth(transfer_eth_model);
        } catch (TTransportException e) {
            logger.error("transfer_eth==>TTransportException====>"+e.getMessage());
        } catch (TException e) {
            logger.error("transfer_eth==>TException====>"+e.getMessage());
        }finally {
            transport.close();
        }
        return returnTransfer;
    }

    /**
     * 獲取eth余額
     * @param https_web3j
     * @param address
     * @return
     */
    public double get_eth_balance(String https_web3j,String address){
        GetServer getServer=new GetServer();
        TTransport transport=getServer.get_transport();
        double balance=0;
        try {
            ETH_CORE.Client client = getServer.open_client(transport);
            balance=client.get_eth_balance(https_web3j,address);
        } catch (TTransportException e) {
            logger.error("get_eth_balance==>TTransportException====>"+e.getMessage());
        } catch (TException e) {
            logger.error("get_eth_balance==>TException====>"+e.getMessage());
        }finally {
            transport.close();
        }
        return balance;
    }

    /**
     * 轉賬sheep
     * @param transfer_sheep_model
     * @return
     */
    public EXCHANGE_RETURN_TRANSFER transfer_sheep(EXCHANGE_TRANSFER_SHEEP_MODEL transfer_sheep_model){
        EXCHANGE_RETURN_TRANSFER returnTransfer=new EXCHANGE_RETURN_TRANSFER();
        GetServer getServer=new GetServer();
        TTransport transport=getServer.get_transport();
        try {
            ETH_CORE.Client client = getServer.open_client(transport);
            returnTransfer=client.transfer_sheep(transfer_sheep_model);
        } catch (TTransportException e) {
            logger.error("transfer_sheep==>TTransportException====>"+e.getMessage());
        } catch (TException e) {
            logger.error("transfer_sheep==>TException====>"+e.getMessage());
        }finally {
            transport.close();
        }
        return returnTransfer;
    }

    /**
     * 獲取sheep余額
     * @param https_web3j
     * @param address
     * @param contract_address
     * @return
     */
    public double get_sheep_balance(String https_web3j,String address,String contract_address){
        GetServer getServer=new GetServer();
        TTransport transport=getServer.get_transport();
        double balance=0;
        try {
            ETH_CORE.Client client = getServer.open_client(transport);
            balance=client.get_sheep_balance(https_web3j,address,contract_address);
        } catch (TTransportException e) {
            logger.error("get_sheep_balance==>TTransportException====>"+e.getMessage());
        } catch (TException e) {
            logger.error("get_sheep_balance==>TException====>"+e.getMessage());
        }finally {
            transport.close();
        }
        return balance;
    }
}

這幾OJBK了

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM