thrift接口定义
namespace java com.tuliing
struct User{
1:i32 id
2:string name
3:i32 age=0
}
service UserService{
User getById(1:i32 id),
bool isExist(1:string name)
}
使用thrift编译器生成c#代码
thrift --gen csharp example.thrift
vs环境thrift配置
是这个不是 apache thrift (适用于core);
开启连接
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using Thrift.Protocol;
using Thrift.Transport;
namespace ClassLibrary3
{
public class Class1
{
[Guid("9A1EAE37-2698-466E-AC0C-0BDA193420E5")]
interface IName
{
[DispId(1)]//为函数的标识:C#代码中必须定义了接口,才可以按照此方法实现调用。
string ShowAge(string age);
string Name { get; set; }
}
[Guid("169B06D6-CFCC-4B65-B04F-8CB3B332A493")]
[ProgId("TestCom1.Show")]//空间+类名 记录到注册表中,给其他语言创建对象用
public class Show : IName
{
public string Name { get; set; }
public string ShowAge(string age)
{
Console.WriteLine($"Age:{age}");
Console.WriteLine("pre start....");
TTransport transport = null;
try
{
transport = new TSocket("localhost", 9090);
TProtocol protocol = new TBinaryProtocol(transport);
UserService.Client client = new UserService.Client(protocol);
transport.Open();
Console.WriteLine("open succ...");
client.isExist("11");
User result = client.getById(1);
Console.WriteLine("Result: " + result);
// 保持应用程序开启
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
finally
{
transport?.Close();
}
return age;
}
}
}
}
项目结构
注册
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\RegAsm.exe /codebase C:\Users\15232\Desktop\vs2022_com\ClassLibrary3\ClassLibrary3\obj\x64\Release\ClassLibrary3.dll
调用
使用import win32com.client,需要pip install pywin32
遇到问题
注册失败:
RegAsm : error RA0000 : 未能加载文件或程序集“Thrift, Version=1.0.0.1, Culture=neutral, PublicKeyToken=null”或它的某一 个依赖项。需要强名称程序集。 (异常来自 HRESULT:0x80131044)
:
https://blog.youkuaiyun.com/woainiainisheng/article/details/133028766