澳门新浦京娱乐场网站-www.146.net-新浦京娱乐场官网
做最好的网站

澳门新浦京娱乐场网站:第贰遍使用小记,轻松

 

Thrift实现C#调用Java开荒步骤详解

本文基于Thrift-0.10,使用Python达成劳务器端,使用Java落成顾客端,演示了Thrift RPC调用示例。Java客商端提供四个字符串参数,Python服务器端计算这七个字符串的相近度,并赶回相通度结果(double类型,范围[0, 1],0表示一时常,1象征完全相像)

国庆放假闲着没事,乱逛,到了Apache的网址上去看了看,按语言浏览开源项目时,竟然见到一些delphi,颇感意外(即使搞到最后才领会好像那玩意儿不援助小编前日干活非常重要用的delphi 7,⊙﹏⊙),就步入看了下,项目名称为Thrift,没见过,新鲜玩意儿,官方介绍如下:

        事情是那般的,在二个新品类中引进了fastdfs,用这个人做一些小数指标寄放依旧非常的低价的,然后在nuget上就找到了八个法斯特DFS的sdk,如下图:

Apache Thrift 是 脸书 达成的后生可畏种高效的、协理多种编程语言的长途服务调用的框架。

好像的跨语言RPC框架还会有ICE、Hessian、Protocol Buffer、Avro等。

 

后生可畏,意况设置

The Apache Thrift software framework, for scalable cross-language services development, combines a software stack with a code generation engine to build services that work efficiently and seamlessly between C , Java, Python, PHP, Ruby, Erlang, Perl, Haskell, C#, Cocoa, JavaScript, Node.js, Smalltalk, OCaml and Delphi and other languages.

澳门新浦京娱乐场网站 1

1 下载Thrift

下载地址:

thrift-0.9.3.exe 用于编写翻译Thrift中间文件生成对应语言代码的工具

thrift-0.9.3.tar.gz 包括Thrift各样语言的源码库,甚至一些测量检验程序代码等

支付碰着:Windows10,PyCharm二〇一六,Anaconda3,Python3.6

简言之:它是用来支付后台服务的框架,可扩展、跨语言,结合了二个软件栈,完成了代码自动生成,在上头一群语言之间构建高速无缝的劳动。

 

2 编写翻译生成.NET库(DLL)和Java库(Jar)

解压thrift-0.9.3.tar.gz文件。

(1) 生成.NET库

开荒工程:E:Thriftthrift-0.9.3libcsharpsrcThrift.sln 编写翻译,即可生成Thrift.dll

自家的情况是VS二〇〇九以致.NET 4.0 

(2) 生成Java库

Java库是通过Ant创设的,须要安装Ant,安装步骤这里就不赘述了。

开垦命令行CD到java库代码所在的门道:E:Thriftthrift-0.9.3libjava(包含build.xml)

下一场径直实施ant命令就可以开采build目录下转移对应的jar文件。

首先安装python 的thrift包:windows张开Anaconda prompt,输入:conda install -c anaconda thrift   安装thrift包。

在网络又google了有的连锁消息,掌握那些原来是盛名的facebook集团支付的用来解决跨语言的服务调用的难点,古板的webservice大概此外的服务调用的回来超级多都是xml或然json等格式,数据量太大了,该项目固然用来缓和这几个主题素材的,它的数额传输能够是依靠二进制流的,所以那点吸引了自个儿,至于具体的亮点什么的可以团结google了。

       一眼就看到了这么些top1的sdk,应该会比较可靠。。。轻松的在等级次序中运用了黄金时代晃没啥难点就摇摇摆摆上线了,然后就正剧了,测验那边反馈说上传了贰个

3 编写thrift中间文件

namespace java test
namespace csharp test
service Hello {   
   string helloString(1:string word)
}

澳门新浦京娱乐场网站,输入:conda list 可查看系统中生机勃勃度安装了怎样包,及包的本子,如下图所示:大家设置的是:thrift-0.10.0

自个儿下边就器重说下Thrift的装置,甚至demo,其实根本时间都花在条件搭建上了。

人工早产,拉下来的时候少了几人,笔者的应用方法是将一群customerid依照bitmap的花样存到byte[]数组传到fastdfs,最后硬着头皮追踪下来开采是以此所谓

4 生成Java和C#独家的接口文件

Thrift-0.9.3.exe –gen java test.thrift

Thrift-0.9.3.exe –gen csharp test.thrift

可以见见在当前目录下会现身转移的呼应代码。

澳门新浦京娱乐场网站 2

下边就从头说怎么搭建情状,作者是在windows xp上做的考试:

的sdk在upload的时候在bytes数组管理上出了bug,那下无助了,哎,nuget上那写sdk的猜测也正是私有写着游戏丢上去的,哪个地方敢用到生产上,幸好在测

5 编写Java服务端代码

新建普通Java项目,将事先ant编写翻译生成的连锁的jar文件(libthrift-0.9.3.jar以致E:Thriftthrift-0.9.3libjavabuildlib目录下有所jar文件)add tobuild path;然后还要将转换的Hello.java也加盟到工程中,注意包名。

(1)首先编写接口完成类:

 

package test;
import org.apache.thrift.TException;
import test.Hello.Iface; 
public classHelloImpl implementsIface{ 
   privatestaticintcount= 0;      
   @Override 
   publicString helloString(String word)throwsTException
   {
        count  = 1; 
        System.out.println("get "   word   " "  count);  
        return "hello "   word   " "   count; 
   }  
}

 

(2)编写寄宿代码,运维并监听在钦赐端口:

package test;
import org.apache.thrift.protocol.TBinaryProtocol;   
import org.apache.thrift.protocol.TBinaryProtocol.Factory;   
import org.apache.thrift.server.TServer;   
import org.apache.thrift.server.TThreadPoolServer;   
import org.apache.thrift.server.TThreadPoolServer.Args;   
import org.apache.thrift.transport.TServerSocket;   
import org.apache.thrift.transport.TTransportException; 
import test.Hello.Processor;

public classServer { 
   @SuppressWarnings({"rawtypes", "unchecked" })
    public void startServer() {   
        try {   
            System.out.println("thrift server host on port 8899"); 
            TServerSocket serverTransport = new TServerSocket(8899);
           Hello.Processorprocess = newProcessor(newHelloImpl());   
            Factory portFactory = newTBinaryProtocol.Factory(true, true);   
            Args args = newArgs(serverTransport);   
            args.processor(process);   
            args.protocolFactory(portFactory);   
            TServer server = newTThreadPoolServer(args);   
            server.serve();   
        } catch (TTransportException e) {   
            e.printStackTrace();   
        }   
   }   

   publicstaticvoidmain(String[] args) {    
        System.out.println("thrift server init"); 
        Server server = new Server();   
        System.out.println("thrift server start"); 
        server.startServer();   
        System.out.println("thrift server end"); 
   }   
} 

澳门新浦京娱乐场网站:第贰遍使用小记,轻松示例。 

在写代码早前,必要先定义一个.thrift文件,然后选择Thrift Compiler生成相应的Thrift服务须要依据的“文件”

1.下载、安装Cygwin(在windows模拟unix的操作情状)

试情况意识了,不然又搜查捕获什么乱子了。

6 编写C#客商端代码

新建普通调整台项目,引进Thrift.dll;然后还要将调换的Hello.cs也参加到工程中。

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Thrift.Transport;
using Thrift.Protocol;
namespace ThriftTest
{
    class ClientTest
    {
        static void Main(string[]args)
        {
            TTransporttransport = new TSocket("localhost", 8899);
            TProtocolprotocol = new TBinaryProtocol(transport);
            test.Hello.Client client = newtest.Hello.Client(protocol);
            transport.Open();
            Console.WriteLine("Client calls client.helloString().....");
            Console.WriteLine(client.helloString("jiyiqin"));
            client.Dispose();
        }
    }
}

①定义.thrift文件

下载地址:

 

7 运行

运行java服务端Server.java:

thrift server init

thrift server start

thrift server host on port 8899

get jiyiqin 1

 

运行C#顾客端代码ClientTest.cs

Client calls client.helloString().....

Hello jiyiqin 1

请按恣意键继续…

能够见见Thrift和ICE等跨语言RPC框架开辟步骤极其肖似,差不离相似,生成的公文也都差不离,不过和依靠Servlet的Hessian这种跨语言RPC框架差异十分大。

 

Apache Thrift 是 Facebook 完成的生龙活虎种高效的、帮忙七种编制程序语言的中远间距服务调用的框架。 相仿的跨语言RPC框架...

namespace py similarityservice
namespace java similarityservice

service ChatSimilarityService{
    double similarity(1:string chat1, 2:string chat2),
}

安装进程中选下安装的路子,也等于它的根目录,笔者选的是C:Program Filescygwin,前面还会有个下载站点的精选,小编选了个edu.cn结尾的,速度尚可,别的就都信守暗中认可一路下来就足以了 

大器晚成:化解办法

namespace提供了风姿浪漫种集体代码的诀窍。其实便是,生成的文件放在:similarityservice那个文件夹下。

2.ant

  难题还得要缓和,可是庆幸的是,fastdfs是Ali的几个大咖YuQing写的,那应该有java的sdk更可信赖一点,用maven的话更有益于。

出于前面包车型客车Python安装的thrift-0.10,由此在官网上下载:thrift-0.10.exe,将它位于与 .thrift相仿的目录下,cmd切换来该目录下,执行命令:

自个儿事先曾经装过了,遭受变量什么的也配过了,所以不要搞了(cygwin对windows的情形变量也能够间接使用)

        <dependency>
            <groupId>net.oschina.zcx7878</groupId>
            <artifactId>fastdfs-client-java</artifactId>
            <version>1.27.0.0</version>
        </dependency>
.thrift-0.10.0.exe --gen py chat_similarity.thrift

3.下载、安装thrift

 

浮动的文件如下,将它们位于合适的python包下,就可以供python 服务端程序 import 了。

         pull下来之后,那个sdk果然是fastdfs的审核人写的,那下子安全感暴增,测量检验了须臾间,那个bug用这一个sdk果然就平昔不难题了。。。兴奋~~~~

澳门新浦京娱乐场网站 3

亟需下载(今后的本子是0.8.0)

澳门新浦京娱乐场网站 4

 

  • thrift-0.8.0.tar.gz [PGP] [MD5]
  • Thrift compiler for Windows (thrift-0.8.0.exe) [PGP] [MD5]

  

二,Python服务端完结

五个都得下在下来,thrift-0.8.0.tar.gz,作者把它内置了cygwin的顾客目录下C:Program FilescygwinhomeJadic Wei下

       然后流程图差非常少就形成了这么些样子。

pycharm thrift插件支持

按互连网海人民广播电视台湾大学版本说的直白解压那些文件,作者起步了Cygwin Terminal(安装后好桌面有神速形式),输入解压命令:

澳门新浦京娱乐场网站 5

可以去pycharm插件官方网站下载多个thrift插件,安装好将来,编写 .thrift 文件能够自动补全提醒。

$ tar -zxvf thrift-0.8.0.tar.gz

 

服务端的贯彻首要有以下五方面:(个人精通,恐怕有错)

赢得如下提示

二:解决C# 和 JAVA的互通难点

①Handler

tar: 它就像是不疑似贰个 tar 归档文件
tar: 跳转到下二个头
tar: 由于前次不当,将上述次的谬误状态退出

  互通方式相当多,除了走rest这种面向http的格局,还足以行使thrift,grpc这种tcp的格局,最终自个儿调整也许采用thrift走大器晚成遭,这段时间风靡的本子是0.11了。

服务端业务管理逻辑。这里就是业务代码,例如总计多少个字符串 相近度

后又得英特网一网上朋友的晋升,那样就消除了,先是:

网址: 看了一下C#的thrift sdk,貌似最高援救0.9.1,网站为: ,

②Processor

$ gunzip thrift-0.8.0.tar.gz

 

从Thrift框架 转移到 业务管理逻辑。由此是RPC调用,顾客端要把 参数发送给服务端,而那总体由Thrift封装起来了,由Processor将选择的“数据”转交给职业逻辑去管理

情趣就是先要gz文件解压, 接着:

澳门新浦京娱乐场网站 6

③Protocol

$ tar -zxvf thrift-0.8.0.tar

澳门新浦京娱乐场网站 7

数据的体系化与反类别化。客商端提供的是“字符串”,而数据传输是叁个个的字节,由此会用到连串化与反体系化。

就解压好了,

 

④Transport

背后根据网络朋友说的正是安装thrift了,

有了这些thrift-0.9.1.exe之后,接下去就可以定义Thrift的DSL,这么些DSL可以让thrift-0.9.1.exe 生成梯次语言版本的sdk。

传输层的多寡传输。

本身参谋了那么些做了下()可独有下边这一步成功了

 

⑤TServer

就是thrift的主目录,然后

  1. 定义Thrift DSL

    service ThriftService {

     string Upload(1: binary data),
     binary Download(1: string path),
     bool Remove(1: string path)
    

    }

服务端的品类。服务器以何种方法来处理客商端乞请,譬喻,二遍Client诉求创立一个新线程呢?还是使用线程池?……可参照他事他说加以调查:卡住通讯之Socket编制程序

./configure

 

TSimpleServer —— 单线程服务器端使用标准的阻塞式 I/O

下边包车型地铁正是推行照旧不行,提醒笔者compiler/cpp是个目录,确实是个目录,作者不掌握是还是不是本人哪边输入的非日常,对linux的事物不打听,然后又上网查了查

 有人只怕会问,这些DSL怎么写,那个大家能够看看官方的DSL的顺序主要词描述的网站:  照旧比较轻便的,如果不知底的

TThreadPoolServer —— 四线程服务器端使用正式的阻塞式 I/O

看来贰个网民说的刚刚上边下载的thrift-0.8.0.exe,这厮为了后边使用方便,改个名,thrift.exe,直接复制到c:windows目录下,搞到了

话,那几个是亲自过问大全:  ,然后保留为1.thrift。

TNonblockingServer —— 四线程服务器端使用非阻塞式 I/O

像这种类型实在就兑现了cygwin中设置thrift的母的,也等于为着前边能够用它来自动生成代码

 

 

 

  1. 通过thrift生成 C# SDK

把地点生成的thrift文件复制到 thrift_service包下,如下图:

上边就能够用了,相仿信守法定的证实本身归纳些个demo,用的是java写的服务端和客商端

 

澳门新浦京娱乐场网站 8

至于怎么根据规范写相同于伪代码的文本,大家可以在互连网看看它的必要标准,作者的事例,文件名d.thrift如下

     生成的艺术能够参照一下官方网站的沙盘:

 

struct User{
    1:required i32 userId,
    2:string userName,
    3:string userPass,
}

service JNBus {
    bool isUserValid(1: string userName, 2: string userPass),
    i32 login(1: string userName, 2: string userPass),
    User getUser(1: i32 userId),
    list<User> getAllUser(),
}    
thrift --gen <language> <Thrift filename>

C:Usershxc>cd C:javalibthrift

C:javalibthrift>thrift-0.9.1.exe -gen csharp C:javalibthrift1.thrift

全总python 服务端的欧洲经济共同体代码如下:

自动生成代码:

澳门新浦京娱乐场网站 9

 1 from thrift.protocol import TBinaryProtocol
 2 from thrift.server import TServer
 3 from thrift.transport import TSocket, TTransport
 4 
 5 from text.thrift_service.similarityservice import ChatSimilarityService
 6 
 7 from difflib import SequenceMatcher
 8 from pypinyin import pinyin
 9 import zhon
10 import pypinyin
11 from zhon.hanzi import punctuation
12 import re
13 
14 __HOST = '127.0.0.1'
15 __PORT = 9090
16 
17 
18 def similar_num(list1, list2):
19     return len(set(list1).intersection(list2))
20 
21 
22 def similar_ration(str1, str2):
23     return SequenceMatcher(lambda x: x == ' ', str1, str2).ratio()
24 
25 class SimilarityHandler(ChatSimilarityService.Iface):
26     def __init__(self):
27         self.log={}
28     def ping(selfs):
29         print('ping')
30 
31     def similarity(self, chat1, chat2):
32         #去掉中文字符串中的特殊标点符号
33         list1 = re.findall('[^{}]'.format(zhon.hanzi.punctuation), chat1)
34         list2 = re.findall('[^{}]'.format(zhon.hanzi.punctuation), chat2)
35 
36         #将标点符号转换成拼音
37         pinyin1 = pinyin(list1, style=pypinyin.STYLE_NORMAL)
38         pinyin2 = pinyin(list2, style=pypinyin.STYLE_NORMAL)
39 
40         #将所有的拼音统一保存到 单个list 中
41         pinyin_list1 = [word[0] for word in pinyin1]
42         pinyin_list2 = [word[0] for word in pinyin2]
43 
44         #计算 list 中元素相同的个数
45         result1 = similar_num(pinyin_list1, pinyin_list2)
46 
47         #list convert to string
48         str1_pinyin = ''.join(pinyin_list1)
49         str2_pinyin = ''.join(pinyin_list2)
50         #计算字符串的相似度
51         result2 = similar_ration(str1_pinyin, str2_pinyin)
52 
53         print('ratio:{}, nums:{}'.format(result2, result1))
54         return result2
55 
56 
57 if __name__ == '__main__':
58     handler = SimilarityHandler()
59     processor = ChatSimilarityService.Processor(handler)
60     transport = TSocket.TServerSocket(host=__HOST, port=__PORT)
61     tfactory = TTransport.TBufferedTransportFactory()
62     pfactory = TBinaryProtocol.TBinaryProtocolFactory()
63 
64     server = TServer.TThreadPoolServer(processor, transport, tfactory, pfactory)
65 
66     print('Starting the server')
67     server.serve()
68     print('done')

开发银行命令行,步向d.thrift所在目录下,试行

 

此间大约地介绍下促成思路:

thrift -gen java d.thrift

  能够看见,实施完未来,就多了三个gen-csharp文件夹,点步入看一下,会意识有一个文本名字为DSL中定义的ThriftService.cs文件。

①行使python 的 zhon 包过滤掉汉语中现身的标点等特殊字符

未曾错的意况下,会扭转二个文书gen-java,里面便是自动生成的代码,生成了八个文件贰个User.java,四个JNBus.java,代码太长了,就不贴了

澳门新浦京娱乐场网站 10

②python的 pypinyin 包 将汉语调换到字符串(其实也得以一贯比较汉语字符串的相仿度,但自身这里调换来了拼音,就也正是比较爱沙尼亚语字符串了)

上边就依据自动生成的文书来写服务端和顾客端了,但在步向前边得写消除二个主题材料,便是thrift运维供给的jar包,那是就供给利用ant了,我是如此做的

 

③应用python 的 difflib 包中的SequenceMatcher 类来测算三个字符串之间的形似度

通过cygwin进入thrift-0.8.0libjava,执行下

3. 通过thrift生成 JAVA SDK

 

ant

     

三,Java顾客端达成

会自行将具备需求的jar包下载下来,放在了build文件夹下,将里面包车型大巴jar包都拷贝出来,以增加到项目中

     实行完上面这条语句,你会意识你的文件夹又多了豆蔻梢头份gen-java 。    

①在maven工程的pom.xml中增加thrift信任。这里的libthrift版本、windows10下载的thrift compiler版本(thrift-0.10.0.exe),还或者有 python的 thrift包的本子 最棒保持风度翩翩致。

究竟走入尾声代码编写了

C:javalibthrift>thrift-0.9.1.exe -gen java C:javalibthrift1.thrift
        <!-- https://mvnrepository.com/artifact/org.apache.thrift/libthrift -->
        <dependency>
            <groupId>org.apache.thrift</groupId>
            <artifactId>libthrift</artifactId>
            <version>0.10.0</version>
        </dependency>

服务端:

 

②cmd命令行实践:.thrift-0.10.0.exe --gen java chat_similarity.thrift  生成 ChatSimilarityService.java 文件,Java 客商端代码须要依靠它。

率先服务的落到实处类:

澳门新浦京娱乐场网站 11

澳门新浦京娱乐场网站 12

 1 import java.util.ArrayList;
 2 import java.util.List;
 3 
 4 import org.apache.thrift.TException;
 5 
 6 import com.jadic.thrift.autoGen.*;
 7 
 8 public class JNBusImpl implements JNBus.Iface{
 9 
10     @Override
11     public boolean isUserValid(String userName, String userPass)
12             throws TException {
13         return userName.equals("Jadic") && userPass.equals("Jadic");
14     }
15 
16     @Override
17     public int login(String userName, String userPass) throws TException {
18         return 99;
19     }
20 
21     @Override
22     public User getUser(int userId) throws TException {
23         User user = new User(userId, "Jadic", "Jadic Is Handsome");
24         return user;
25     }
26 
27     @Override
28     public List<User> getAllUser() throws TException {
29         List<User> users = new ArrayList<User>();
30         User user = new User(1, "1", "1");
31         users.add(user);
32         user = new User(2, "2", "2");
33         users.add(user);
34         return users;
35     }
36 
37 }

               

 

开发银行服务的主类:

三:SDK集成

大器晚成体Java Client的代码如下:

 1 import org.apache.thrift.server.TServer;
 2 import org.apache.thrift.server.TSimpleServer;
 3 import org.apache.thrift.transport.TServerSocket;
 4 import org.apache.thrift.transport.TServerTransport;
 5 import org.apache.thrift.transport.TTransportException;
 6 
 7 import com.jadic.thrift.autoGen.JNBus;
 8 import com.jadic.thrift.autoGen.JNBus.Iface;
 9 import com.jadic.thrift.autoGen.JNBus.Processor;
10 
11 public class JNBusServer {
12 
13     private JNBusImpl jnBusImpl;
14     private JNBus.Processor<Iface> processor;
15     
16     public JNBusServer() {
17         jnBusImpl = new JNBusImpl();
18         processor = new Processor<JNBus.Iface>(jnBusImpl);
19     }
20     
21     public void startServer() throws TTransportException {
22         TServerTransport serverTransport = new TServerSocket(9090);
23         TServer server = new TSimpleServer(new TServer.Args(serverTransport).processor(processor));
24         System.out.println("Starting the simple server...");
25         server.serve();
26     }
27     
28     public static void main(String[] args) throws TTransportException {
29         JNBusServer jnBusServer = new JNBusServer();
30         jnBusServer.startServer();
31     }
32 }

   改善之后,大家接纳JAVA作为服务端,C#旅居户端,服务端要做的职业正是通过JAVA来封装法斯特DFS,然后让C#来调用。

 1 import thrift.similarityservice.ChatSimilarityService;
 2 import org.apache.thrift.TException;
 3 import org.apache.thrift.protocol.TBinaryProtocol;
 4 import org.apache.thrift.protocol.TProtocol;
 5 import org.apache.thrift.transport.TSocket;
 6 import org.apache.thrift.transport.TTransport;
 7 
 8 /**
 9  * Created by Administrator on 2017/12/20.
10  */
11 public class SimilarityThriftClient {
12 
13     public static void main(String[] args) {
14         try {
15             TTransport transport;
16             transport = new TSocket("127.0.0.1", 9090);
17             transport.open();
18 
19             TProtocol protocol = new TBinaryProtocol(transport);
20             ChatSimilarityService.Client client = new ChatSimilarityService.Client(protocol);
21             perform(client);
22             transport.close();
23 
24         } catch (TException e) {
25             e.printStackTrace();
26         }
27     }
28     private static void perform(ChatSimilarityService.Client client)throws TException {
29         String chat1 = "您好。";
30         String chat2 = "你好";
31         double ratio = client.similarity(chat1, chat2);
32         System.out.println(ratio);
33     }
34 }

 

 

 

客户端:

  1. JAVA服务端

四,总结

 1 import java.util.List;
 2 
 3 import org.apache.thrift.TException;
 4 import org.apache.thrift.protocol.TBinaryProtocol;
 5 import org.apache.thrift.protocol.TProtocol;
 6 import org.apache.thrift.transport.TSocket;
 7 import org.apache.thrift.transport.TTransport;
 8 
 9 import com.jadic.thrift.autoGen.JNBus;
10 import com.jadic.thrift.autoGen.User;
11 import com.jadic.thrift.autoGen.JNBus.Client;
12 
13 public class JNBusClient {
14     
15     public static void main(String[] args) throws TException {
16         TTransport transport = new TSocket("localhost", 9090);
17         transport.open();
18         TProtocol protocol = new TBinaryProtocol(transport);
19         JNBus.Client client = new Client(protocol);
20         log("isUserValid return "   client.isUserValid("Jadic", "Jadic"));
21         log("login return "   client.login("Jadic", "Jadic"));
22         User user = client.getUser(12);
23         log("getUser return "   user.toString());
24         List<User> users = client.getAllUser();
25         log("getAllUser return "   users.size()   " user");
26         for (User u : users) {
27             log(u.toString());
28         }
29     }
30     
31     public static void log(Object msg) {
32         System.out.println(msg);
33     }
34 
35 }

《1》使用fastDFS 和 Thrift的Maven地址:

本文介绍了一个简短的 Python Server、Java Client的Thrift服务调用示例。关于Thrift可参照他事他说加以考察:

起步服务端,顾客端,客商端调用成功,打字与印刷如下:

        <!-- https://mvnrepository.com/artifact/org.apache.thrift/libthrift -->
        <dependency>
            <groupId>org.apache.thrift</groupId>
            <artifactId>libthrift</artifactId>
            <version>0.9.1</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/net.oschina.zcx7878/fastdfs-client-java -->
        <dependency>
            <groupId>net.oschina.zcx7878</groupId>
            <artifactId>fastdfs-client-java</artifactId>
            <version>1.27.0.0</version>
        </dependency>

Thrift Tutorial

isUserValid return true
login return 99
getUser return User(userId:12, userName:Jadic, userPass:Jadic Is Handsome)
getAllUser return 2 user
User(userId:1, userName:1, userPass:1)
User(userId:2, userName:2, userPass:2)

 

Apache Thrift - 可伸缩的跨语言服务开垦框架

发端的调用终于成功了

《2》 ThriftServiceImpl.java 实现类:

Thrift 安装及选择

  1 package com.datamip.thrift;
  2 
  3 import java.io.IOException;
  4 import java.nio.ByteBuffer;
  5 import java.util.Date;
  6 
  7 import org.apache.log4j.Logger;
  8 import org.apache.thrift.TException;
  9 import org.csource.common.MyException;
 10 import org.csource.fastdfs.StorageClient;
 11 
 12 import com.fasterxml.jackson.databind.ObjectMapper;
 13 
 14 /*
 15  * thrift 服务端
 16  */
 17 public class ThriftServiceImpl implements ThriftService.Iface {
 18 
 19     public static Logger logger1 = Logger.getLogger(App.class);
 20     
 21     StorageClient client = null;
 22     
 23     ObjectMapper objectMapper=new ObjectMapper();
 24 
 25     public ThriftServiceImpl() throws IOException, MyException {
 26         client = new FastService().Create();
 27     }
 28 
 29     //上传文件
 30     public String Upload(ByteBuffer data) {
 31         
 32         byte[] bytes = data.array();
 33 
 34         logger1.info("已成功接受到upload请求: bytes.length=" bytes.length);
 35 
 36         if(bytes==null || bytes.length==0) return "";
 37         
 38         // 目前给的 “后缀名为 g1",以后可以动态变更,通过‘阿波罗’动态配置
 39         String[] result = null;
 40 
 41         try {
 42             result = client.upload_file(bytes, "g1", null);
 43             
 44             logger1.info("update 上传结果为: " objectMapper.writeValueAsString(result));
 45             
 46             if (result.length < 2) return "";
 47 
 48         }catch (Exception e) {
 49             logger1.error("upload异常",e);
 50         }
 51 
 52         return result[1];
 53     }
 54 
 55     // 文件下载
 56     public ByteBuffer Download(String path) throws TException {
 57 
 58         logger1.info("已成功接受到download请求:" path);
 59     
 60         if (path == null || path == "")
 61             return ByteBuffer.allocate(0);
 62 
 63         String[] arr = path.split("\.");
 64     
 65         if (arr.length < 2)
 66             return ByteBuffer.allocate(0);
 67 
 68         String group_name = arr[1];
 69 
 70         try {
 71             byte[] bytes = client.download_file(group_name, path);
 72             
 73             logger1.info(String.format("根据path=%s,获取的bytes长度为:%s",path,bytes.length));
 74 
 75             return ByteBuffer.wrap(bytes);
 76 
 77         }catch (Exception e) {
 78             logger1.error("download异常",e);
 79         }
 80 
 81         // TODO Auto-generated method stub
 82         return ByteBuffer.allocate(0);
 83     }
 84 
 85     // 删除文件
 86     public boolean Remove(String path) throws TException {
 87 
 88         logger1.info("已成功接受到remove请求:" path);
 89         
 90         if (path == null || path == "") return false;
 91 
 92         String[] arr = path.split("\.");
 93         
 94         if(arr==null || arr.length<2) return false;
 95 
 96         String group_name = arr[1];
 97 
 98         try {
 99             int code = client.delete_file(group_name, path);
100             
101             logger1.info(String.format("当前path=%s, groupname=%s,返回状态值=%s",
102                                        path,group_name,code));
103             
104             if(code==0) {
105                 return true;
106             }
107             
108         }catch (Exception e) {
109             logger1.error("Remove异常",e);
110         }
111 
112         return false;
113     }
114 }

 

 

原文:Python Thrift 轻松示例

《3》 法斯特DFS的封装类

 1 package com.datamip.thrift;
 2 
 3 import java.io.IOException;
 4 
 5 import org.csource.common.MyException;
 6 import org.csource.fastdfs.ClientGlobal;
 7 import org.csource.fastdfs.StorageClient;
 8 import org.csource.fastdfs.StorageServer;
 9 import org.csource.fastdfs.TrackerClient;
10 import org.csource.fastdfs.TrackerServer;
11 
12 import com.datamip.utils.PropertiesUtils;
13 
14 public class FastService {
15 
16     public StorageClient Create() throws IOException, MyException {
17 
18         //读取配置文件
19         String path = PropertiesUtils.getProperties("setting.properties","fastdfs");
20         return this.Create(path);
21     }
22 
23     public StorageClient Create(String host) throws IOException, MyException {
24 
25         ClientGlobal.initByTrackers(host);
26 
27         // 3、创建一个TrackerClient对象。
28         TrackerClient trackerClient = new TrackerClient();
29 
30         // 4、创建一个TrackerServer对象。
31         TrackerServer trackerServer = trackerClient.getConnection();
32 
33         // 5、声明一个StorageServer对象,null。
34         StorageServer storageServer = null;
35 
36         // 6、获得StorageClient对象。
37         StorageClient storageClient = new StorageClient(trackerServer, storageServer);
38 
39         return storageClient;
40     }
41 }

 

《4》末了正是AppMain,Thrift开启壹玖玖柒9端口。

 1 package com.datamip.thrift;
 2 
 3 import java.io.IOException;
 4 
 5 import org.apache.log4j.Logger;
 6 import org.apache.thrift.TProcessor;
 7 import org.apache.thrift.protocol.TBinaryProtocol;
 8 import org.apache.thrift.server.TServer;
 9 import org.apache.thrift.server.TSimpleServer;
10 import org.apache.thrift.transport.TServerSocket;
11 import org.apache.thrift.transport.TTransportException;
12 import org.csource.common.MyException;
13 
14 public class App {
15 
16     public static Logger logger1 = Logger.getLogger(App.class);
17      
18     public static void main(String[] args) throws IOException, MyException {
19          
20         try {            
21             TProcessor tprocessor = new ThriftService.Processor<ThriftService.Iface>(new ThriftServiceImpl());
22 
23             TServerSocket serverTransport = new TServerSocket(9999);
24             TServer.Args tArgs = new TServer.Args(serverTransport);
25 
26             tArgs.processor(tprocessor);
27             tArgs.protocolFactory(new TBinaryProtocol.Factory());
28 
29             logger1.debug("thrift 服务端开启,开放端口 19999");
30             
31             TServer server = new TSimpleServer(tArgs);
32             server.serve();
33         } catch (TTransportException e) {
34             e.printStackTrace();
35         }
36     }
37 }

 

  1. C#客户端

《1》 从negut上把dll拉下来,然后把调换的ThriftService.cs引进到大家的解决方案中

澳门新浦京娱乐场网站 13澳门新浦京娱乐场网站 14

  public partial class ThriftService
    {
        public interface Iface
        {
            string Upload(byte[] data);
#if SILVERLIGHT
    IAsyncResult Begin_Upload(AsyncCallback callback, object state, byte[] data);
    string End_Upload(IAsyncResult asyncResult);
#endif
            byte[] Download(string path);
#if SILVERLIGHT
    IAsyncResult Begin_Download(AsyncCallback callback, object state, string path);
    byte[] End_Download(IAsyncResult asyncResult);
#endif
            bool Remove(string path);
#if SILVERLIGHT
    IAsyncResult Begin_Remove(AsyncCallback callback, object state, string path);
    bool End_Remove(IAsyncResult asyncResult);
#endif
        }

        public class Client : IDisposable, Iface
        {
            public Client(TProtocol prot) : this(prot, prot)
            {
            }

            public Client(TProtocol iprot, TProtocol oprot)
            {
                iprot_ = iprot;
                oprot_ = oprot;
            }

            protected TProtocol iprot_;
            protected TProtocol oprot_;
            protected int seqid_;

            public TProtocol InputProtocol
            {
                get { return iprot_; }
            }
            public TProtocol OutputProtocol
            {
                get { return oprot_; }
            }


            #region " IDisposable Support "
            private bool _IsDisposed;

            // IDisposable
            public void Dispose()
            {
                Dispose(true);
            }


            protected virtual void Dispose(bool disposing)
            {
                if (!_IsDisposed)
                {
                    if (disposing)
                    {
                        if (iprot_ != null)
                        {
                            ((IDisposable)iprot_).Dispose();
                        }
                        if (oprot_ != null)
                        {
                            ((IDisposable)oprot_).Dispose();
                        }
                    }
                }
                _IsDisposed = true;
            }
            #endregion



#if SILVERLIGHT
    public IAsyncResult Begin_Upload(AsyncCallback callback, object state, byte[] data)
    {
      return send_Upload(callback, state, data);
    }

    public string End_Upload(IAsyncResult asyncResult)
    {
      oprot_.Transport.EndFlush(asyncResult);
      return recv_Upload();
    }

#endif

            public string Upload(byte[] data)
            {
#if !SILVERLIGHT
                send_Upload(data);
                return recv_Upload();

#else
      var asyncResult = Begin_Upload(null, null, data);
      return End_Upload(asyncResult);

#endif
            }
#if SILVERLIGHT
    public IAsyncResult send_Upload(AsyncCallback callback, object state, byte[] data)
#else
            public void send_Upload(byte[] data)
#endif
            {
                oprot_.WriteMessageBegin(new TMessage("Upload", TMessageType.Call, seqid_));
                Upload_args args = new Upload_args();
                args.Data = data;
                args.Write(oprot_);
                oprot_.WriteMessageEnd();
#if SILVERLIGHT
      return oprot_.Transport.BeginFlush(callback, state);
#else
                oprot_.Transport.Flush();
#endif
            }

            public string recv_Upload()
            {
                TMessage msg = iprot_.ReadMessageBegin();
                if (msg.Type == TMessageType.Exception)
                {
                    TApplicationException x = TApplicationException.Read(iprot_);
                    iprot_.ReadMessageEnd();
                    throw x;
                }
                Upload_result result = new Upload_result();
                result.Read(iprot_);
                iprot_.ReadMessageEnd();
                if (result.__isset.success)
                {
                    return result.Success;
                }
                throw new TApplicationException(TApplicationException.ExceptionType.MissingResult, "Upload failed: unknown result");
            }


#if SILVERLIGHT
    public IAsyncResult Begin_Download(AsyncCallback callback, object state, string path)
    {
      return send_Download(callback, state, path);
    }

    public byte[] End_Download(IAsyncResult asyncResult)
    {
      oprot_.Transport.EndFlush(asyncResult);
      return recv_Download();
    }

#endif

            public byte[] Download(string path)
            {
#if !SILVERLIGHT
                send_Download(path);
                return recv_Download();

#else
      var asyncResult = Begin_Download(null, null, path);
      return End_Download(asyncResult);

#endif
            }
#if SILVERLIGHT
    public IAsyncResult send_Download(AsyncCallback callback, object state, string path)
#else
            public void send_Download(string path)
#endif
            {
                oprot_.WriteMessageBegin(new TMessage("Download", TMessageType.Call, seqid_));
                Download_args args = new Download_args();
                args.Path = path;
                args.Write(oprot_);
                oprot_.WriteMessageEnd();
#if SILVERLIGHT
      return oprot_.Transport.BeginFlush(callback, state);
#else
                oprot_.Transport.Flush();
#endif
            }

            public byte[] recv_Download()
            {
                TMessage msg = iprot_.ReadMessageBegin();
                if (msg.Type == TMessageType.Exception)
                {
                    TApplicationException x = TApplicationException.Read(iprot_);
                    iprot_.ReadMessageEnd();
                    throw x;
                }
                Download_result result = new Download_result();
                result.Read(iprot_);
                iprot_.ReadMessageEnd();
                if (result.__isset.success)
                {
                    return result.Success;
                }
                throw new TApplicationException(TApplicationException.ExceptionType.MissingResult, "Download failed: unknown result");
            }


#if SILVERLIGHT
    public IAsyncResult Begin_Remove(AsyncCallback callback, object state, string path)
    {
      return send_Remove(callback, state, path);
    }

    public bool End_Remove(IAsyncResult asyncResult)
    {
      oprot_.Transport.EndFlush(asyncResult);
      return recv_Remove();
    }

#endif

            public bool Remove(string path)
            {
#if !SILVERLIGHT
                send_Remove(path);
                return recv_Remove();

#else
      var asyncResult = Begin_Remove(null, null, path);
      return End_Remove(asyncResult);

#endif
            }
#if SILVERLIGHT
    public IAsyncResult send_Remove(AsyncCallback callback, object state, string path)
#else
            public void send_Remove(string path)
#endif
            {
                oprot_.WriteMessageBegin(new TMessage("Remove", TMessageType.Call, seqid_));
                Remove_args args = new Remove_args();
                args.Path = path;
                args.Write(oprot_);
                oprot_.WriteMessageEnd();
#if SILVERLIGHT
      return oprot_.Transport.BeginFlush(callback, state);
#else
                oprot_.Transport.Flush();
#endif
            }

            public bool recv_Remove()
            {
                TMessage msg = iprot_.ReadMessageBegin();
                if (msg.Type == TMessageType.Exception)
                {
                    TApplicationException x = TApplicationException.Read(iprot_);
                    iprot_.ReadMessageEnd();
                    throw x;
                }
                Remove_result result = new Remove_result();
                result.Read(iprot_);
                iprot_.ReadMessageEnd();
                if (result.__isset.success)
                {
                    return result.Success;
                }
                throw new TApplicationException(TApplicationException.ExceptionType.MissingResult, "Remove failed: unknown result");
            }

        }
        public class Processor : TProcessor
        {
            public Processor(Iface iface)
            {
                iface_ = iface;
                processMap_["Upload"] = Upload_Process;
                processMap_["Download"] = Download_Process;
                processMap_["Remove"] = Remove_Process;
            }

            protected delegate void ProcessFunction(int seqid, TProtocol iprot, TProtocol oprot);
            private Iface iface_;
            protected Dictionary<string, ProcessFunction> processMap_ = new Dictionary<string, ProcessFunction>();

            public bool Process(TProtocol iprot, TProtocol oprot)
            {
                try
                {
                    TMessage msg = iprot.ReadMessageBegin();
                    ProcessFunction fn;
                    processMap_.TryGetValue(msg.Name, out fn);
                    if (fn == null)
                    {
                        TProtocolUtil.Skip(iprot, TType.Struct);
                        iprot.ReadMessageEnd();
                        TApplicationException x = new TApplicationException(TApplicationException.ExceptionType.UnknownMethod, "Invalid method name: '"   msg.Name   "'");
                        oprot.WriteMessageBegin(new TMessage(msg.Name, TMessageType.Exception, msg.SeqID));
                        x.Write(oprot);
                        oprot.WriteMessageEnd();
                        oprot.Transport.Flush();
                        return true;
                    }
                    fn(msg.SeqID, iprot, oprot);
                }
                catch (IOException)
                {
                    return false;
                }
                return true;
            }

            public void Upload_Process(int seqid, TProtocol iprot, TProtocol oprot)
            {
                Upload_args args = new Upload_args();
                args.Read(iprot);
                iprot.ReadMessageEnd();
                Upload_result result = new Upload_result();
                result.Success = iface_.Upload(args.Data);
                oprot.WriteMessageBegin(new TMessage("Upload", TMessageType.Reply, seqid));
                result.Write(oprot);
                oprot.WriteMessageEnd();
                oprot.Transport.Flush();
            }

            public void Download_Process(int seqid, TProtocol iprot, TProtocol oprot)
            {
                Download_args args = new Download_args();
                args.Read(iprot);
                iprot.ReadMessageEnd();
                Download_result result = new Download_result();
                result.Success = iface_.Download(args.Path);
                oprot.WriteMessageBegin(new TMessage("Download", TMessageType.Reply, seqid));
                result.Write(oprot);
                oprot.WriteMessageEnd();
                oprot.Transport.Flush();
            }

            public void Remove_Process(int seqid, TProtocol iprot, TProtocol oprot)
            {
                Remove_args args = new Remove_args();
                args.Read(iprot);
                iprot.ReadMessageEnd();
                Remove_result result = new Remove_result();
                result.Success = iface_.Remove(args.Path);
                oprot.WriteMessageBegin(new TMessage("Remove", TMessageType.Reply, seqid));
                result.Write(oprot);
                oprot.WriteMessageEnd();
                oprot.Transport.Flush();
            }

        }


#if !SILVERLIGHT
        [Serializable]
#endif
        public partial class Upload_args : TBase
        {
            private byte[] _data;

            public byte[] Data
            {
                get
                {
                    return _data;
                }
                set
                {
                    __isset.data = true;
                    this._data = value;
                }
            }


            public Isset __isset;
#if !SILVERLIGHT
            [Serializable]
#endif
            public struct Isset
            {
                public bool data;
            }

            public Upload_args()
            {
            }

            public void Read(TProtocol iprot)
            {
                TField field;
                iprot.ReadStructBegin();
                while (true)
                {
                    field = iprot.ReadFieldBegin();
                    if (field.Type == TType.Stop)
                    {
                        break;
                    }
                    switch (field.ID)
                    {
                        case 1:
                            if (field.Type == TType.String)
                            {
                                Data = iprot.ReadBinary();
                            }
                            else
                            {
                                TProtocolUtil.Skip(iprot, field.Type);
                            }
                            break;
                        default:
                            TProtocolUtil.Skip(iprot, field.Type);
                            break;
                    }
                    iprot.ReadFieldEnd();
                }
                iprot.ReadStructEnd();
            }

            public void Write(TProtocol oprot)
            {
                TStruct struc = new TStruct("Upload_args");
                oprot.WriteStructBegin(struc);
                TField field = new TField();
                if (Data != null && __isset.data)
                {
                    field.Name = "data";
                    field.Type = TType.String;
                    field.ID = 1;
                    oprot.WriteFieldBegin(field);
                    oprot.WriteBinary(Data);
                    oprot.WriteFieldEnd();
                }
                oprot.WriteFieldStop();
                oprot.WriteStructEnd();
            }

            public override string ToString()
            {
                StringBuilder sb = new StringBuilder("Upload_args(");
                sb.Append("Data: ");
                sb.Append(Data);
                sb.Append(")");
                return sb.ToString();
            }

        }


#if !SILVERLIGHT
        [Serializable]
#endif
        public partial class Upload_result : TBase
        {
            private string _success;

            public string Success
            {
                get
                {
                    return _success;
                }
                set
                {
                    __isset.success = true;
                    this._success = value;
                }
            }


            public Isset __isset;
#if !SILVERLIGHT
            [Serializable]
#endif
            public struct Isset
            {
                public bool success;
            }

            public Upload_result()
            {
            }

            public void Read(TProtocol iprot)
            {
                TField field;
                iprot.ReadStructBegin();
                while (true)
                {
                    field = iprot.ReadFieldBegin();
                    if (field.Type == TType.Stop)
                    {
                        break;
                    }
                    switch (field.ID)
                    {
                        case 0:
                            if (field.Type == TType.String)
                            {
                                Success = iprot.ReadString();
                            }
                            else
                            {
                                TProtocolUtil.Skip(iprot, field.Type);
                            }
                            break;
                        default:
                            TProtocolUtil.Skip(iprot, field.Type);
                            break;
                    }
                    iprot.ReadFieldEnd();
                }
                iprot.ReadStructEnd();
            }

            public void Write(TProtocol oprot)
            {
                TStruct struc = new TStruct("Upload_result");
                oprot.WriteStructBegin(struc);
                TField field = new TField();

                if (this.__isset.success)
                {
                    if (Success != null)
                    {
                        field.Name = "Success";
                        field.Type = TType.String;
                        field.ID = 0;
                        oprot.WriteFieldBegin(field);
                        oprot.WriteString(Success);
                        oprot.WriteFieldEnd();
                    }
                }
                oprot.WriteFieldStop();
                oprot.WriteStructEnd();
            }

            public override string ToString()
            {
                StringBuilder sb = new StringBuilder("Upload_result(");
                sb.Append("Success: ");
                sb.Append(Success);
                sb.Append(")");
                return sb.ToString();
            }

        }


#if !SILVERLIGHT
        [Serializable]
#endif
        public partial class Download_args : TBase
        {
            private string _path;

            public string Path
            {
                get
                {
                    return _path;
                }
                set
                {
                    __isset.path = true;
                    this._path = value;
                }
            }


            public Isset __isset;
#if !SILVERLIGHT
            [Serializable]
#endif
            public struct Isset
            {
                public bool path;
            }

            public Download_args()
            {
            }

            public void Read(TProtocol iprot)
            {
                TField field;
                iprot.ReadStructBegin();
                while (true)
                {
                    field = iprot.ReadFieldBegin();
                    if (field.Type == TType.Stop)
                    {
                        break;
                    }
                    switch (field.ID)
                    {
                        case 1:
                            if (field.Type == TType.String)
                            {
                                Path = iprot.ReadString();
                            }
                            else
                            {
                                TProtocolUtil.Skip(iprot, field.Type);
                            }
                            break;
                        default:
                            TProtocolUtil.Skip(iprot, field.Type);
                            break;
                    }
                    iprot.ReadFieldEnd();
                }
                iprot.ReadStructEnd();
            }

            public void Write(TProtocol oprot)
            {
                TStruct struc = new TStruct("Download_args");
                oprot.WriteStructBegin(struc);
                TField field = new TField();
                if (Path != null && __isset.path)
                {
                    field.Name = "path";
                    field.Type = TType.String;
                    field.ID = 1;
                    oprot.WriteFieldBegin(field);
                    oprot.WriteString(Path);
                    oprot.WriteFieldEnd();
                }
                oprot.WriteFieldStop();
                oprot.WriteStructEnd();
            }

            public override string ToString()
            {
                StringBuilder sb = new StringBuilder("Download_args(");
                sb.Append("Path: ");
                sb.Append(Path);
                sb.Append(")");
                return sb.ToString();
            }

        }


#if !SILVERLIGHT
        [Serializable]
#endif
        public partial class Download_result : TBase
        {
            private byte[] _success;

            public byte[] Success
            {
                get
                {
                    return _success;
                }
                set
                {
                    __isset.success = true;
                    this._success = value;
                }
            }


            public Isset __isset;
#if !SILVERLIGHT
            [Serializable]
#endif
            public struct Isset
            {
                public bool success;
            }

            public Download_result()
            {
            }

            public void Read(TProtocol iprot)
            {
                TField field;
                iprot.ReadStructBegin();
                while (true)
                {
                    field = iprot.ReadFieldBegin();
                    if (field.Type == TType.Stop)
                    {
                        break;
                    }
                    switch (field.ID)
                    {
                        case 0:
                            if (field.Type == TType.String)
                            {
                                Success = iprot.ReadBinary();
                            }
                            else
                            {
                                TProtocolUtil.Skip(iprot, field.Type);
                            }
                            break;
                        default:
                            TProtocolUtil.Skip(iprot, field.Type);
                            break;
                    }
                    iprot.ReadFieldEnd();
                }
                iprot.ReadStructEnd();
            }

            public void Write(TProtocol oprot)
            {
                TStruct struc = new TStruct("Download_result");
                oprot.WriteStructBegin(struc);
                TField field = new TField();

                if (this.__isset.success)
                {
                    if (Success != null)
                    {
                        field.Name = "Success";
                        field.Type = TType.String;
                        field.ID = 0;
                        oprot.WriteFieldBegin(field);
                        oprot.WriteBinary(Success);
                        oprot.WriteFieldEnd();
                    }
                }
                oprot.WriteFieldStop();
                oprot.WriteStructEnd();
            }

            public override string ToString()
            {
                StringBuilder sb = new StringBuilder("Download_result(");
                sb.Append("Success: ");
                sb.Append(Success);
                sb.Append(")");
                return sb.ToString();
            }

        }


#if !SILVERLIGHT
        [Serializable]
#endif
        public partial class Remove_args : TBase
        {
            private string _path;

            public string Path
            {
                get
                {
                    return _path;
                }
                set
                {
                    __isset.path = true;
                    this._path = value;
                }
            }


            public Isset __isset;
#if !SILVERLIGHT
            [Serializable]
#endif
            public struct Isset
            {
                public bool path;
            }

            public Remove_args()
            {
            }

            public void Read(TProtocol iprot)
            {
                TField field;
                iprot.ReadStructBegin();
                while (true)
                {
                    field = iprot.ReadFieldBegin();
                    if (field.Type == TType.Stop)
                    {
                        break;
                    }
                    switch (field.ID)
                    {
                        case 1:
                            if (field.Type == TType.String)
                            {
                                Path = iprot.ReadString();
                            }
                            else
                            {
                                TProtocolUtil.Skip(iprot, field.Type);
                            }
                            break;
                        default:
                            TProtocolUtil.Skip(iprot, field.Type);
                            break;
                    }
                    iprot.ReadFieldEnd();
                }
                iprot.ReadStructEnd();
            }

            public void Write(TProtocol oprot)
            {
                TStruct struc = new TStruct("Remove_args");
                oprot.WriteStructBegin(struc);
                TField field = new TField();
                if (Path != null && __isset.path)
                {
                    field.Name = "path";
                    field.Type = TType.String;
                    field.ID = 1;
                    oprot.WriteFieldBegin(field);
                    oprot.WriteString(Path);
                    oprot.WriteFieldEnd();
                }
                oprot.WriteFieldStop();
                oprot.WriteStructEnd();
            }

            public override string ToString()
            {
                StringBuilder sb = new StringBuilder("Remove_args(");
                sb.Append("Path: ");
                sb.Append(Path);
                sb.Append(")");
                return sb.ToString();
            }

        }


#if !SILVERLIGHT
        [Serializable]
#endif
        public partial class Remove_result : TBase
        {
            private bool _success;

            public bool Success
            {
                get
                {
                    return _success;
                }
                set
                {
                    __isset.success = true;
                    this._success = value;
                }
            }


            public Isset __isset;
#if !SILVERLIGHT
            [Serializable]
#endif
            public struct Isset
            {
                public bool success;
            }

            public Remove_result()
            {
            }

            public void Read(TProtocol iprot)
            {
                TField field;
                iprot.ReadStructBegin();
                while (true)
                {
                    field = iprot.ReadFieldBegin();
                    if (field.Type == TType.Stop)
                    {
                        break;
                    }
                    switch (field.ID)
                    {
                        case 0:
                            if (field.Type == TType.Bool)
                            {
                                Success = iprot.ReadBool();
                            }
                            else
                            {
                                TProtocolUtil.Skip(iprot, field.Type);
                            }
                            break;
                        default:
                            TProtocolUtil.Skip(iprot, field.Type);
                            break;
                    }
                    iprot.ReadFieldEnd();
                }
                iprot.ReadStructEnd();
            }

            public void Write(TProtocol oprot)
            {
                TStruct struc = new TStruct("Remove_result");
                oprot.WriteStructBegin(struc);
                TField field = new TField();

                if (this.__isset.success)
                {
                    field.Name = "Success";
                    field.Type = TType.Bool;
                    field.ID = 0;
                    oprot.WriteFieldBegin(field);
                    oprot.WriteBool(Success);
                    oprot.WriteFieldEnd();
                }
                oprot.WriteFieldStop();
                oprot.WriteStructEnd();
            }

            public override string ToString()
            {
                StringBuilder sb = new StringBuilder("Remove_result(");
                sb.Append("Success: ");
                sb.Append(Success);
                sb.Append(")");
                return sb.ToString();
            }

        }

    }

View Code

《2》 封装贰个轻巧易行的CUHighlanderD操作

  1     public class ThriftSHelper
  2     {
  3         private static string fastdfs = ConfigurationManager.AppSettings["fastdfs"];
  4 
  5         TTransport transport = null;
  6         TProtocol protocol = null;
  7         ThriftService.Client client = null;
  8 
  9         public ThriftSHelper()
 10         {
 11             var arr = fastdfs.Split(':');
 12             var host = arr[0];
 13             var port = Convert.ToInt32(arr[1]);
 14 
 15             transport = new TSocket(host, port);
 16             protocol = new TBinaryProtocol(transport);
 17             client = new ThriftService.Client(protocol);
 18         }
 19 
 20         public static ThriftSHelper Create()
 21         {
 22             return new ThriftSHelper();
 23         }
 24 
 25         public string UploadFile(BitArray bit)
 26         {
 27             string path = string.Empty;
 28 
 29             try
 30             {
 31                 var bytes = new byte[Convert.ToInt32(Math.Ceiling((double)bit.Length / 8))];
 32 
 33                 transport.Open();
 34 
 35                 bit.CopyTo(bytes, 0);
 36 
 37                 path = client.Upload(bytes);
 38             }
 39             catch (Exception ex)
 40             {
 41                 LogHelper.Error(ex);
 42             }
 43             finally
 44             {
 45                 transport.Close();
 46             }
 47 
 48             return path;
 49         }
 50 
 51         /// <summary>
 52         /// 下载文件
 53         /// </summary>
 54         /// <param name="fileName"></param>
 55         /// <returns></returns>
 56         public BitArray DownloadFile(string fileName)
 57         {
 58             BitArray bitArray = null;
 59 
 60             try
 61             {
 62                 transport.Open();
 63 
 64                 var bytes = client.Download(fileName);
 65 
 66                 return new BitArray(bytes);
 67             }
 68             catch (Exception ex)
 69             {
 70                 LogHelper.WriteLog(fileName, ex);
 71             }
 72             finally
 73             {
 74                 transport.Close();
 75             }
 76 
 77             return bitArray;
 78         }
 79 
 80         /// <summary>
 81         /// 删除文件
 82         /// </summary>
 83         /// <param name="fileName"></param>
 84         public void RemoveFile(string fileName)
 85         {
 86             try
 87             {
 88                 transport.Open();
 89 
 90                 client.Remove(fileName);
 91             }
 92             catch (Exception ex)
 93             {
 94                 LogHelper.WriteLog(ex);
 95             }
 96             finally
 97             {
 98                 transport.Close();
 99             }
100         }
101     }

 

  好了,这几个难点大家就像此完美灭绝了,跑在生育上或许非常好的。

 

本文由澳门新浦京娱乐场网站发布于www.146.net,转载请注明出处:澳门新浦京娱乐场网站:第贰遍使用小记,轻松