转载至 https://headsigned.com/posts/csharp-apache-thrift-demo/
This demo application shows how to implement a simple Apache Thrift client/server in C#.
Thrift is a software framework that enables creation of services that can be served and consumed by many different languages. This article is not a tutorial for Thrift, nor for the Thrift interface definition language - these you can find on the official tutorial pages.
You can download the source code or check it out at GitHub. Visual C# 2010 Express was used to create the solution.
How the demo works
There are 3 projects in the solution - Common, Server, and Client. Project ‘Common’ contains code that is shared by both client and server. This includes the code generated by the thrift compiler from the demo-interface.thrift file:
// demo-interface.thrift
namespace * Common.ThriftInterface
struct BookInfo
{
1: i32 Id,
2: string Author,
3: string Title
}
service LibraryService
{
list<BookInfo> GetAllBooks();
BookInfo GetBook(1: i32 bookId);
}
The Thrift compiler will compile this code into two classes: BookInfo and LibraryService. This is done as a part of the Common project pre-build step by invoking the VendorThrift.0.9.1.3 ools hrift-0.9.1.exe.
Server
In order to expose the LibraryService, LibraryServiceHandler implements the generated LibraryService.Iface:
// LibraryServiceHandler.cs internal class LibraryServiceHandler : LibraryService.Iface { // <snip> public List<BookInfo> GetAllBooks() { /* <snip> */ } public BookInfo GetBook(int bookId) { /* <snip> */ } }
An instance of this handler is passed to the LibraryService.Processor, and is served by starting a Thrift server:
// Server var handler = new LibraryServiceHandler(); var processor = new LibraryService.Processor(handler); TServerTransport transport = new TServerSocket(9090); TServer server = new TThreadPoolServer(processor, transport); server.Serve();
Client
Connecting a client and consuming the service is also quite simple. You only need to know the address, port, and protocol of the server. In the demo application, out TThreadPoolServer uses the default protocol, which is binary:
// Client var transport = new TSocket("localhost", 9090); var protocol = new TBinaryProtocol(transport); var client = new LibraryService.Client(protocol); transport.Open(); var allBooks = client.GetAllBooks(); // Actual Thrift call var firstBook = client.GetBook(allBooks.First().Id); // Actual Thrift call
This simple client/server demo shows how easy it is to get started with Thrift and C#. To learn more, check out the missing guide.