您的位置:新葡亰496net > 奥门新萄京娱乐场 > 新葡亰496net第二次利用小记,轻易示例

新葡亰496net第二次利用小记,轻易示例

发布时间:2019-11-30 06:11编辑:奥门新萄京娱乐场浏览(175)

     

    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 是 Twitter 达成的后生可畏种高效的、援救各种编制程序语言的中远间隔服务调用的框架。

    就好像的跨语言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.

    新葡亰496net 1

    1 下载Thrift

    下载地址:

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

    thrift-0.9.3.tar.gz 满含Thrift各样语言的源码库,以至部分测量检验程序代码等

    支付情状:Windows10,PyCharm2014,Anaconda3,Python3.6

    简言之:它是用来支付后台服务的框架,可扩张、跨语言,结合了二个软件栈,落成了代码自动生成,在上边一批语言之间营造便捷无缝的劳务。

     

    2 编写翻译生成.NET库(DLL卡塔尔和Java库(Jar卡塔尔国

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

    (1) 生成.NET库

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

    自家的情状是VS2009以致.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

    能够见到在当前目录下会并发变化的呼应代码。

    新葡亰496net 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的操作情况卡塔尔(英语:State of Qatar)

    试际遇意识了,不然又搜查缉获什么乱子了。

    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 是 Twitter 达成的风姿浪漫种高效的、帮衬各种编制程序语言的远程服务调用的框架。 相仿的跨语言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果然就不曾难题了。。。快乐~~~~

    新葡亰496net 3

    内需下载(以往的版本是0.8.0卡塔尔(英语:State of Qatar)

    新葡亰496net 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(安装后好桌面有神速格局卡塔尔(قطر‎,输入解压命令:

    新葡亰496net 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了。

    服务端业务处理逻辑。这里就是职业代码,举例总括多少个字符串 相像度

    新葡亰496net第二次利用小记,轻易示例。后又得英特网一网民的唤起,这样就化解了,先是:

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

    ②Processor

    $ gunzip thrift-0.8.0.tar.gz

     

    从Thrift框架 转移到 业务处理逻辑。因而是RPC调用,顾客端要把 参数发送给服务端,而那整个由Thrift封装起来了,由Processor将收取的“数据”转交给工作逻辑去管理

    意思正是先要gz文件解压, 接着:

    新葡亰496net 6

    ③Protocol

    $ tar -zxvf thrift-0.8.0.tar

    新葡亰496net 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写的服务端和顾客端

     

    新葡亰496net 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 服务端的完全代码如下:

    自动生成代码:

    新葡亰496net 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,代码太长了,就不贴了

    新葡亰496net 10

    ②python的 pypinyin 包 将中文调换到字符串(其实也得以一向相比中文字符串的相仿度,但自己那边变换来了拼音,就相当于比较乌Crane语字符串了)

    上边就凭借自动生成的公文来写服务端和客户端了,但在步入前边得写消除一个标题,就是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 客商端代码须求重视它。

    率先服务的落实类:

    新葡亰496net 11

    新葡亰496net 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开启19979端口。

     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引进到大家的解决方案中

    新葡亰496net 13新葡亰496net 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》 封装三个洗练的CU奥德赛D操作

      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     }
    

     

      好了,那个标题大家宛如此完善消除了,跑在生养上还是非常好的。

     

    本文由新葡亰496net发布于奥门新萄京娱乐场,转载请注明出处:新葡亰496net第二次利用小记,轻易示例

    关键词:

上一篇:没有了

下一篇:没有了