接口定义文件
module TestApp
{
interface Hello
{
string hello(int no, string name);
};
};
如何通过接口定义文件生成对应的类文件
pom.xml文件中增加tars的插件,具体内容如下
<build>
<plugins>
<plugin>
<groupId>com.tencent.tars</groupId>
<artifactId>tars-maven-plugin</artifactId>
<version>${project.parent.version}</version>
<configuration>
<tars2JavaConfig>
<tarsFiles>
<tarsFile>${basedir}/src/main/resources/hello.tars</tarsFile>
</tarsFiles>
<tarsFileCharset>UTF-8</tarsFileCharset>
<servant>false</servant>
<srcPath>${basedir}/src/main/java</srcPath>
<charset>UTF-8</charset>
<packagePrefixName>com.qq.tars.quickstart.server.</packagePrefixName>
</tars2JavaConfig>
</configuration>
</plugin>
</plugins>
</build>
执行命令
mvn tars:tars2java
自动会在对应的目录生成java类。
servant参数说明
<servant>false</servant>
- true:只生成服务器代码
- false:只生成客户端代码
- 未设置:服务器和客户端代码都生成
接口文件生产的代码
HelloPrx 客户端代理接口
@Servant
public interface HelloPrx {
public String hello(int no, String name);
CompletableFuture<String> promise_hello(int no, String name);
public String hello(int no, String name, @TarsContext java.util.Map<String, String> ctx);
public void async_hello(@TarsCallback HelloPrxCallback callback, int no, String name);
public void async_hello(@TarsCallback HelloPrxCallback callback, int no, String name, @TarsContext java.util.Map<String, String> ctx);
}
HelloPrxCallback 客户端异步调用回调类
@Servant
public abstract class HelloPrxCallback extends TarsAbstractCallback {
public abstract void callback_hello(String ret);
}
HelloServant 服务器端接口
@Servant
public interface HelloServant {
String hello(int no, String name);
}
客户端调用接口方式
初始化代理
// 配置文件
CommunicatorConfig cfg = new CommunicatorConfig();
// 通过工厂类获取Communicator
Communicator communicator = CommunicatorFactory.getInstance().getCommunicator(cfg);
// 获取接口代理类的实例
HelloPrx proxy = communicator.stringToProxy(HelloPrx.class, "TestApp.HelloJavaServer.HelloObj@tcp -h 192.168.10.115 -p 15050 -t 60000");
同步调用(Synchronous call)
String ret = proxy.hello(1000, "Hello World");
一次调用(One-way call)
proxy.async_hello(null, 1000, "Hello World");
异步调用(Asynchronous call)
proxy.async_hello(new HelloPrxCallback() {
@Override
public void callback_expired() {
}
@Override
public void callback_exception(Throwable ex) {
}
@Override
public void callback_hello(String ret) {
Main.logger.info("invoke use async {}", ret);
}
}, 1000, "Hello World");
promise异步调用(Asynchronous call)
proxy.promise_hello(1000, "hello world").thenCompose(x -> {
logger.info("invoke use promise {}", x);
return CompletableFuture.completedFuture(0);
});