thrift筆記----大致上thrift知識

thrift相似java裏面的socket和sockchannel中server和client通訊java

thrift最重要的是跨語言,裏面提供了序列化和反序列化、json和實體對象等方法apache

Apache Thrift軟件框架(用於可擴展的跨語言服務開發)將軟件堆棧與代碼生成引擎結合在一塊兒,
以構建可在C++, Java, Python, PHP, Ruby, Erlang, Perl, Haskell, C#, Cocoa, JavaScript, Node.js, Smalltalk, OCaml and Delphi 
等語言

裏面大概方法json

圖片轉其餘地方服務器

 

 

 數據類型框架

bool:布爾值,對應 Java 的 boolean
byte8 位有符號整數,對應 Java 的 byte
i16:16 位有符號整數,對應 Java 的 short
i32:32 位有符號整數,對應 Java 的 int
i64:64 位有符號整數,對應 Java 的 long
double64 位浮點數,對應 Java 的 double
string:文本或二進制字符串,對應 Java 的 String
struct:定義公共的對象,在 Java 中是一個 JavaBean
list:對應 Java 的 ArrayList
set:對應 Java 的 HashSet
map:對應 Java 的 HashMap
exception:對應 Java 的 Exception
service:service 類型能夠被繼承
enum:枚舉類型

 

maven導入jarsocket

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

 

 

新建thrift文件maven

(thrift命名例如UserService.thriftide

namespace java com.test.libthrift.demo2
struct UserInfo{
     1:optional i32 id;
     2:optional string key;
     3:optional string value;
}
service UserService {
  bool isLogin(1:string username,2:string password)
  UserInfo setUserInfo(1:UserInfo user)
  string setStr(1:string str)
  list<UserInfo> setuserInfos(1:list<UserInfo> li)
}

生成接口編碼

給客戶端庫和所編寫的服務器使用,複製到服務端和客戶端項目裏spa

例如

thrift -r -gen java UserService.thrift

thrift --gen <語言> <Thrift 文件名>

 

序列化

                    TSerializer serializer = new TSerializer(new TSimpleJSONProtocol.Factory());
                    UserInfo user = new UserInfo();
                    user.setId(100);
                    user.setKey("key01");
                    user.setValue("value值");
                    String json = serializer.toString(user);

反序列

        TDeserializer deserializer = new TDeserializer(new TSimpleJSONProtocol.Factory());
        UserInfo base =new UserInfo();
        deserializer.deserialize(base, str,"UTF-8");

 

服務端實現接口

package com.test.libthrift.demo2;

import java.util.List;

import org.apache.thrift.TDeserializer;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TSimpleJSONProtocol;

public class UserServiceImpl implements UserService.Iface{

    @Override
    public boolean isLogin(String username, String password) throws TException {
        // TODO Auto-generated method stub
        System.out.println("收到客戶端:"+username+"---"+password);
        if(username==null ||password==null) return false;
        if("lyx".equals(username)&&"123456".equals(password)) return true;
        
        return false;
    }

    @Override
    public UserInfo setUserInfo(UserInfo user) throws TException {
        // TODO Auto-generated method stub
        System.out.println("收到客戶端UserInfo:"+user.toString());
        return user;
    }

    @Override
    public String setStr(String str) throws TException {
        // TODO Auto-generated method stub
        System.out.println("收到客戶端str:"+str);

        TDeserializer deserializer = new TDeserializer(new TSimpleJSONProtocol.Factory());
        UserInfo base =new UserInfo();
        deserializer.deserialize(base, str,"UTF-8");
        System.out.println("反序列化:"+base.toString());
        return str;
    }

    @Override
    public List<UserInfo> setuserInfos(List<UserInfo> li) throws TException {
        // TODO Auto-generated method stub
        System.out.println("收到客戶端LIST:");
        for(UserInfo u : li){
            System.out.println(u.toString());
        }
        return li;
    }


}
View Code

服務端啓動服務

package com.test.libthrift.demo2.server;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TCompactProtocol;
import org.apache.thrift.server.TNonblockingServer;
import org.apache.thrift.server.TServer;
import org.apache.thrift.server.TSimpleServer;
import org.apache.thrift.server.TThreadedSelectorServer;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TNonblockingServerSocket;
import org.apache.thrift.transport.TServerSocket;
import org.apache.thrift.transport.TTransportException;

import com.test.libthrift.demo2.UserService;
import com.test.libthrift.demo2.UserServiceImpl;

public class uServerSocket {

    public static void main(String[] args) throws TTransportException {
        // TODO Auto-generated method stub
/*        TServerSocket serversocket = new TServerSocket(20000);
        //服務的接口
        TServer.Args arg = new TServer.Args(serversocket);
        arg.processor(new UserService.Processor<UserService.Iface>(new UserServiceImpl()));
        arg.protocolFactory(new TBinaryProtocol.Factory());
        TServer server = new TSimpleServer(arg);
        server.serve();*/
        
        // 非阻塞方式  
        TNonblockingServerSocket serversocket = new TNonblockingServerSocket(20000);
        //服務的接口
//        TNonblockingServer.Args
        TThreadedSelectorServer.Args arg = new TThreadedSelectorServer.Args(serversocket);
        arg.processor(new UserService.Processor<UserService.Iface>(new UserServiceImpl()));
        // 設置協議工廠,高效率的、密集的二進制編碼格式進行數據傳輸協議
        arg.protocolFactory(new TCompactProtocol.Factory());
        // 設置傳輸工廠,使用非阻塞方式,按塊的大小進行傳輸,相似於Java中的NIO
        arg.transportFactory(new TFramedTransport.Factory());
        // 多個線程,主要負責客戶端的IO處理
        arg.selectorThreads(2);
        // 工做線程池
        ExecutorService pool = Executors.newFixedThreadPool(3);
        
        arg.executorService(pool);
        TThreadedSelectorServer server = new TThreadedSelectorServer(arg);
        System.out.println("Starting server .....");
        server.serve();
        
    }

}
View Code

 

客戶端鏈接服務端

package com.test.libthrift.demo2.client;

import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.thrift.TBase;
import org.apache.thrift.TException;
import org.apache.thrift.TSerializer;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TCompactProtocol;
import org.apache.thrift.protocol.TJSONProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.protocol.TSimpleJSONProtocol;
import org.apache.thrift.transport.TFastFramedTransport;
import org.apache.thrift.transport.TIOStreamTransport;
import org.apache.thrift.transport.TMemoryInputTransport;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;

import com.test.libthrift.demo2.UserInfo;
import com.test.libthrift.demo2.UserService;

public class uSocketClient {

/*    public static void main(String[] args) {
        // TODO Auto-generated method stub
        TTransport socket = new TSocket("127.0.0.1", 20000, 30000);
        // 協議要和服務端一致
        TProtocol  protocol = new TBinaryProtocol(socket);
        UserService.Client client = new UserService.Client(protocol);
        try {
            socket.open();
        } catch (TTransportException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        try {
            boolean b = client.isLogin("", "");
            System.out.println("收到服務端:"+b);
            if(b ==false){
                try {
                    Thread.sleep(12000);
                    
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                b = client.isLogin("lyx", "123456");
                System.out.println("收到服務端:"+b);
            }
        } catch (TException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
              System.out.println("close");
              socket.close();
        }
        
        
    }*/
  
    
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        TTransport socket =new TFastFramedTransport(  new TSocket("127.0.0.1", 20000, 30000));
        // 協議要和服務端一致
        TProtocol  protocol = new TCompactProtocol(socket);
        UserService.Client client = new UserService.Client(protocol);
        try {
            socket.open();
        } catch (TTransportException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        try {
            boolean b = client.isLogin("", "");
            System.out.println("收到服務端:"+b);
            if(b ==false){
                try {
                    Thread.sleep(12000);
                    
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                b = client.isLogin("lyx", "123456");
                System.out.println("收到服務端:"+b);
                
                try {
                    Thread.sleep(10000);
                    System.out.println("發送user");
                    TSerializer serializer = new TSerializer(new TSimpleJSONProtocol.Factory());
                    UserInfo user = new UserInfo();
                    user.setId(100);
                    user.setKey("key01");
                    user.setValue("value值");
                    String json = serializer.toString(user);
                    System.out.println("json String:"+json);
                    System.out.println("發送str json");
                    client.setStr(json);
                    System.out.println("發送usrInfo");
                    client.setUserInfo(user);
                    List<UserInfo> list =new ArrayList<UserInfo>();
                    for(int i=1;i<101;i++){
                        user = new UserInfo();
                        user.setId(i);
                        user.setKey("key"+i);
                        user.setValue("value值"+i);
                        list.add(user);
                    }
                    client.setuserInfos(list);
                    
                    try {
                        socket.write(json.getBytes("UTF-8"));
                    } catch (UnsupportedEncodingException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    System.out.println("發送user結束");
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                
            }
        } catch (TException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
              System.out.println("close");
              socket.close();
        }
        
        
    }
    

}
View Code
相關文章
相關標籤/搜索