Thrift notes - basically thrift knowledge

Keywords: Apache Java socket JSON

thrift is similar to socket in java and communication between server and client in sockchannel

The most important thing about thrift is cross language, which provides methods such as serialization and deserialization, json and entity objects

The Apache Thrift software framework (for extensible cross language service development) combines the software stack with the code generation engine,
It can be built in C + +, Java, python, PHP, ruby, Erlang, Perl, Haskell, cා, cocoa, JavaScript, node.js, Smalltalk, Ocaml and Delphi
Other languages

How to do it

Picture to other places

 

 

Data type

bool: boolean value, corresponding to Java's boolean
 Byte: 8-bit signed integer, corresponding to Java byte
 i16: 16 bit signed integer, corresponding to Java short
 i32: 32-bit signed integer, corresponding to Java int
 i64: 64 bit signed integer, corresponding to Java long
 Double: 64 bit floating-point number, corresponding to Java double
 String: text or binary string, corresponding to Java string
 struct: defines a public object, which is a JavaBean in Java
 list: ArrayList corresponding to Java
 set: the HashSet corresponding to Java
 map: HashMap corresponding to Java
 Exception: exception corresponding to Java
 Service: service type can be inherited
 enum: enumeration type

 

maven import jar

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

 

 

New thrift file

(name thrift for example UserService.thrift)

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)
}

Generation interface

It is used for the client library and the written server and copied to the server and client project

for example

thrift -r -gen java UserService.thrift

Thrift -- Gen < language > < thrift filename >

 

serialize

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

Inverse sequence

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

 

Server implementation interface

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("Received client:"+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("Client received UserInfo:"+user.toString());
        return user;
    }

    @Override
    public String setStr(String str) throws TException {
        // TODO Auto-generated method stub
        System.out.println("Client received str:"+str);

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

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


}
View Code

Server start service

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);
        //Service interface
        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();*/
        
        // Non blocking mode  
        TNonblockingServerSocket serversocket = new TNonblockingServerSocket(20000);
        //Service interface
//        TNonblockingServer.Args
        TThreadedSelectorServer.Args arg = new TThreadedSelectorServer.Args(serversocket);
        arg.processor(new UserService.Processor<UserService.Iface>(new UserServiceImpl()));
        // Set up a protocol factory, high efficiency and intensive binary coding format for data transmission protocol
        arg.protocolFactory(new TCompactProtocol.Factory());
        // Set up the transmission factory, use non blocking mode, and transfer by block size, similar to Java Medium NIO
        arg.transportFactory(new TFramedTransport.Factory());
        // Multiple threads, mainly responsible for the client's IO Handle
        arg.selectorThreads(2);
        // Worker pool
        ExecutorService pool = Executors.newFixedThreadPool(3);
        
        arg.executorService(pool);
        TThreadedSelectorServer server = new TThreadedSelectorServer(arg);
        System.out.println("Starting server .....");
        server.serve();
        
    }

}
View Code

 

Client connection server

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);
        // The protocol should be consistent with the server
        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("Receive the server: "+ 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("Receive the server: "+ 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));
        // The protocol should be consistent with the server
        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("Received from server:"+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("Received from server:"+b);
                
                try {
                    Thread.sleep(10000);
                    System.out.println("Send out user");
                    TSerializer serializer = new TSerializer(new TSimpleJSONProtocol.Factory());
                    UserInfo user = new UserInfo();
                    user.setId(100);
                    user.setKey("key01");
                    user.setValue("value value");
                    String json = serializer.toString(user);
                    System.out.println("json String:"+json);
                    System.out.println("Send out str json");
                    client.setStr(json);
                    System.out.println("Send out 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 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("Send out user End");
                } 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

Posted by therealchuckles on Sun, 12 Apr 2020 08:31:08 -0700