블로그 이미지
lilla

Recent Comment

Recent Trackback

Archive

calendar

        1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30  
  • 265,761total
  • 32today
  • 45yesterday
2012.07.15 12:18 android

tutorial.zip


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.


<장점>

- 버전닝 지원
- 여러 언어에서 사용 가능하며 언어에 맞도록 소스가 생성되고, 언어간의 Serialization 가능
- Sync, Async Server API 제공
- XML 설정이 필요 없음
- Layer에 맞는 Interface를 사용 및 Customizing 구축 가능
- RPC 기능 제공 (Google Protocol Buffer에는 없는 기능)
- 서버 기능 좋음
    -- 서블릿 제공(org.apache.thrift.server.TServlet)
   -- 멀티쓰레드 지원 (org.apache.thrift.server.ThreadPoolServer : worker thread 지정)
   -- Async 지원 (org.apache.thrift.server. TNonblockingServer : single threaded)
   -- Multi-thread Half-Sync/Half-Async지원 : org.apache.thrift.server. THsHaServer
   -- Exception을 제공 (Google Protocol Buffer에는 없는 기능)
   -- Set, Map 지원 (Google Protocol Buffer에는 없는 기능)

 

 

 <단점>

- 자바로 코드가 생성될 때, Slf4j를 기본적으로 가지고 가며, 내부 코드는 모두 thrift lib가 필요함
- C++의 Server threading part는 Boost에 의존을 가짐
- 자바 쪽 이클립스 플러그인 없음
- Thrift lib의 api가 자주 바뀌어서, 버전 업마다 소스를 좀 보고 코딩해야 함. (인터넷 예제가 거의 없음)

   인터넷 예제랑 달라서, 컴파일 에러 안나게 하는게 귀찮음...
- XML Serialization/Deserialization 기능 없음
- 문서가 확실히 적음 
- 생성된 코드가 Google Protocol Buffer에 비해서 보기는 편하지는 않음 (특히 C++)


Debian or Ubuntu setup

The following command install all the required tools and libraries to build and install the Apache Thrift compiler on a Debian/Ubuntu Linux based system.

sudo apt-get install libboost-dev libboost-test-dev libboost-program-options-dev libevent-dev automake libtool flex bison pkg-config g++ libssl-dev 

Then install the Java JDK of your choice. Type javac to see a list of available packages, pick the one you prefer and apt-get install it.

Debian Lenny Users need some packages from backports

sudo apt-get -t lenny-backports install automake libboost-test-dev

Optional packages

Some other packages depend on what languages you want Thrift to support.

  • Ruby
    • ruby-full ruby-dev librspec-ruby rake rubygems libdaemons-ruby libgemplugin-ruby mongrel
  • Python
    • python-dev python-twisted
  • Perl
    • libbit-vector-perl
  • Php, install
    • php5-dev php5-cli
  • C_glib
    • libglib2.0-dev
  • Erlang
    • erlang-base erlang-eunit erlang-dev
  • Csharp
    • mono-gmcs libmono-dev libmono-system-web2.0-cil
  • Haskell
    • ghc6 cabal-install libghc6-binary-dev libghc6-network-dev libghc6-http-dev
  • Thrift Compiler for Windows
    • mingw32 mingw32-binutils mingw32-runtime



0. thrift 빌드하기 
 http://thrift.apache.org/download/
ubuntu  환경
1
2
3
$ ./configure
$ make
$ sudo make install

1. 언어지원 라이브러리 만들기 ( perl , python )

  • perl 모듈 설치  

  • perl  라이브러리 빌드 
1
2
3
4
$ cd ~/thrift-0.7.0/lib/perl
$ perl Makefile.PL
$ make
$ sudo make install

  • python 모듈 설치

$sudo apt-get install python-dev python-twisted


  • python 
1
2
3
4
$ cd ~/thrift-0.7.0/lib/perl
$ make
$ sudo python setup.py install




2. tutorial.thrift 파일을 이용해  언어별 코드 생성하기 
1. 서버 ( perl )
$ cd ~/thrift-0.7.0/tutorial
$ thrift -r --gen perl tutorial.thrift
2. 클라이언트 (python)
$ cd ~/thrift-0.7.0/tutorial
$ thrift -r --gen py tutorial.thrift

tutorial.thrift

/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

# Thrift Tutorial
# Mark Slee (mcslee@facebook.com)
#
# This file aims to teach you how to use Thrift, in a .thrift file. Neato. The
# first thing to notice is that .thrift files support standard shell comments.
# This lets you make your thrift file executable and include your Thrift build
# step on the top line. And you can place comments like this anywhere you like.
#
# Before running this file, you will need to have installed the thrift compiler
# into /usr/local/bin.

/**
 * The first thing to know about are types. The available types in Thrift are:
 *
 *  bool        Boolean, one byte
 *  byte        Signed byte
 *  i16         Signed 16-bit integer
 *  i32         Signed 32-bit integer
 *  i64         Signed 64-bit integer
 *  double      64-bit floating point value
 *  string      String
 *  binary      Blob (byte array)
 *  map  Map from one type to another
 *  list    Ordered list of one type
 *  set     Set of unique elements of one type
 *
 * Did you also notice that Thrift supports C style comments?
 */

// Just in case you were wondering... yes. We support simple C comments too.

/**
 * Thrift files can reference other Thrift files to include common struct
 * and service definitions. These are found using the current path, or by
 * searching relative to any paths specified with the -I compiler flag.
 *
 * Included objects are accessed using the name of the .thrift file as a
 * prefix. i.e. shared.SharedObject
 */
include "shared.thrift"

/**
 * Thrift files can namespace, package, or prefix their output in various
 * target languages.
 */
namespace cpp tutorial
namespace java tutorial
namespace php tutorial
namespace perl tutorial

/**
 * Thrift lets you do typedefs to get pretty names for your types. Standard
 * C style here.
 */
typedef i32 MyInteger

/**
 * Thrift also lets you define constants for use across languages. Complex
 * types and structs are specified using JSON notation.
 */
const i32 INT32CONSTANT = 9853
const map MAPCONSTANT = {'hello':'world', 'goodnight':'moon'}

/**
 * You can define enums, which are just 32 bit integers. Values are optional
 * and start at 1 if not supplied, C style again.
 */
enum Operation {
  ADD = 1,
  SUBTRACT = 2,
  MULTIPLY = 3,
  DIVIDE = 4
}

/**
 * Structs are the basic complex data structures. They are comprised of fields
 * which each have an integer identifier, a type, a symbolic name, and an
 * optional default value.
 *
 * Fields can be declared "optional", which ensures they will not be included
 * in the serialized output if they aren't set.  Note that this requires some
 * manual management in some languages.
 */
struct Work {
  1: i32 num1 = 0,
  2: i32 num2,
  3: Operation op,
  4: optional string comment,
}

/**
 * Structs can also be exceptions, if they are nasty.
 */
exception InvalidOperation {
  1: i32 what,
  2: string why
}

/**
 * Ahh, now onto the cool part, defining a service. Services just need a name
 * and can optionally inherit from another service using the extends keyword.
 */
service Calculator extends shared.SharedService {

  /**
   * A method definition looks like C code. It has a return type, arguments,
   * and optionally a list of exceptions that it may throw. Note that argument
   * lists and exception lists are specified using the exact same syntax as
   * field lists in struct or exception definitions.
   */

   void ping(),

   i32 add(1:i32 num1, 2:i32 num2),

   i32 calculate(1:i32 logid, 2:Work w) throws (1:InvalidOperation ouch),

   /**
    * This method has a oneway modifier. That means the client only makes
    * a request and does not listen for any response at all. Oneway methods
    * must be void.
    */
   oneway void zip()

}

/**
 * That just about covers the basics. Take a look in the test/ folder for more
 * detailed examples. After you run this file, your generated code shows up
 * in folders with names gen-. The generated code isn't too scary
 * to look at. It even has pretty indentation.
 */


Client python

#!/usr/bin/env python

#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#

import sys
sys.path.append('../gen-py')

from tutorial import Calculator
from tutorial.ttypes import *

from thrift import Thrift
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol

try:

  # Make socket
  transport = TSocket.TSocket('localhost', 9090)

  # Buffering is critical. Raw sockets are very slow
  transport = TTransport.TBufferedTransport(transport)

  # Wrap in a protocol
  protocol = TBinaryProtocol.TBinaryProtocol(transport)

  # Create a client to use the protocol encoder
  client = Calculator.Client(protocol)

  # Connect!
  transport.open()

  client.ping()
  print 'ping()'

  sum = client.add(1,1)
  print '1+1=%d' % (sum)

  work = Work()

  work.op = Operation.DIVIDE
  work.num1 = 1
  work.num2 = 0

  try:
    quotient = client.calculate(1, work)
    print 'Whoa? You know how to divide by zero?'
  except InvalidOperation, io:
    print 'InvalidOperation: %r' % io

  work.op = Operation.SUBTRACT
  work.num1 = 15
  work.num2 = 10

  diff = client.calculate(1, work)
  print '15-10=%d' % (diff)

  log = client.getStruct(1)
  print 'Check log: %s' % (log.value)

  # Close!
  transport.close()

except Thrift.TException, tx:
  print '%s' % (tx.message)


Server perl

#!/usr/bin/perl

#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#

use strict;
use lib '../gen-perl';
use Thrift::Socket;
use Thrift::Server;
use tutorial::Calculator;

package CalculatorHandler;
use base qw(tutorial::CalculatorIf);

sub new {
    my $classname = shift;
    my $self      = {};

    return bless($self,$classname);
}


sub ping
{
  print "ping()\n";
}

sub add
{
  my($self, $n1, $n2) = @_;
  printf("add(%d,%d)\n", $n1, $n2);
  return $n1 + $n2;
}

sub calculate
{
  my($self, $logid, $work) = @_;
  my $op   = $work->{op};
  my $num1 = $work->{num1};
  my $num2 = $work->{num2};
  printf("calculate(%d, %d %d %d)\n", $logid, $num1, $num2, $op);

  my $val;

  if ($op == tutorial::Operation::ADD) {
    $val = $num1 + $num2;
  } elsif ($op == tutorial::Operation::SUBTRACT) {
    $val = $num1 - $num2;
  } elsif ($op == tutorial::Operation::MULTIPLY) {
    $val = $num1 * $num2;
  } elsif ($op == tutorial::Operation::DIVIDE) {
    if ($num2 == 0)
    {
      my $x = new tutorial::InvalidOperation;
      $x->what($op);
      $x->why('Cannot divide by 0');
      die $x;
    }
    $val = $num1 / $num2;
  } else {
    my $x = new tutorial::InvalidOperation;
    $x->what($op);
    $x->why('Invalid operation');
    die $x;
  }

  my $log = new shared::SharedStruct;
  $log->key($logid);
  $log->value(int($val));
  $self->{log}->{$logid} = $log;

  return $val;
}

sub getStruct
{
  my($self, $key) = @_;
  printf("getStruct(%d)\n", $key);
  return $self->{log}->{$key};
}

sub zip
{
  my($self) = @_;
  print "zip()\n";
}



eval {
  my $handler       = new CalculatorHandler;
  my $processor     = new tutorial::CalculatorProcessor($handler);
  my $serversocket  = new Thrift::ServerSocket(9090);
  my $forkingserver = new Thrift::ForkingServer($processor, $serversocket);
  print "Starting the server...\n";
  $forkingserver->serve();
  print "done.\n";
}; if ($@) {
  if ($@ =~ m/TException/ and exists $@->{message}) {
    my $message = $@->{message};
    my $code    = $@->{code};
    my $out     = $code . ':' . $message;
    die $out;
  } else {
    die $@;
  }
}



수행화면

  • perl 작성된 server 실행 


  • python 으로 작성된 client 실행  ( 더하기 , 나누기 빼기, 메세지 출력 함수 요청  )

  • perl 작성된 server 와 python으로 작성된 client 통신 후 



<


posted by linuxian lilla