转载

thrift笔记—-大体上thrift知识

thrift类似java里面的socket和sockchannel中server和client通信

thrift最重要的是跨语言,里面提供了序列化和反序列化、json和实体对象等方法

Apache Thrift软件框架(用于可扩展的跨语言服务开发)将软件堆栈与代码生成引擎结合在一起,
以构建可在C++, Java, Python, PHP, Ruby, Erlang, Perl, Haskell, C#, Cocoa, JavaScript, Node.js, Smalltalk, OCaml and Delphi 
等语言

里面大概方法

图片转其他地方

thrift笔记—-大体上thrift知识

数据类型

bool:布尔值,对应 Java 的 boolean
byte:8 位有符号整数,对应 Java 的 byte
i16:16 位有符号整数,对应 Java 的 short
i32:32 位有符号整数,对应 Java 的 int
i64:64 位有符号整数,对应 Java 的 long
double:64 位浮点数,对应 Java 的 double
string:文本或二进制字符串,对应 Java 的 String
struct:定义公共的对象,在 Java 中是一个 JavaBean
list:对应 Java 的 ArrayList
set:对应 Java 的 HashSet
map:对应 Java 的 HashMap
exception:对应 Java 的 Exception
service:service 类型可以被继承
enum:枚举类型

maven导入jar

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

新建thrift文件

(thrift命名例如 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)
}

生成接口

给客户端库和所编写的服务器使用,复制到服务端和客户端项目里

例如

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
 
原文  https://www.maiyewang.com/archives/90727
正文到此结束
Loading...