Tars-Spring-boot 使用说明

    依赖配置

    使用此功能需要添加依赖,在pom.xml中添加如下配置:

    在spring boot中,需要通过注解开启tars服务相关功能:

    1. @EnableTarsServer
    2. public class QuickStartApplication {
    3. public static void main(String[] args) {
    4. SpringApplication.run(QuickStartApplication.class, args);
    5. }
    6. }

    通过注解@EnableTarsServer标识这是一个TARS服务,并开启服务相关功能。

    编写tars协议文件,如:

    1. module TestApp
    2. {
    3. interface Hello
    4. {
    5. string hello(int no, string name);
    6. };
    7. };

    服务逻辑通过实现接口来编写:

    1. @TarsServant("HelloObj")
    2. public class HelloServantImpl implements HelloServant {
    3. @Override
    4. return String.format("hello no=%s, name=%s, time=%s", no, name, System.currentTimeMillis());
    5. }
    6. }

    接口的实现类通过注解@TarsServant来暴露服务,其中填写的’HelloObj’为servant名,该名称与管理平台上的名称对应即可。

    此外如果你想使用spring-boot来编写一个http服务,而不使用taf接口的话也是可以的:

    1. @SpringBootApplication
    2. @TarsHttpService("HttpObj")
    3. @RestController
    4. public class DemoApplication {
    5. public static void main(String[] args) {
    6. SpringApplication.run(DemoApplication.class, args);
    7. }
    8. @RequestMapping(path = "/test")
    9. public String test() {
    10. return "hello world";
    11. }
    12. }

    此时添加一个@TarsHttpService注解,这个注解中需要添加你希望绑定的非tars协议 servant的名称,框架会自动将spring-boot中嵌入的容器的端口绑定到对应Servant的端口上,这样你就可以方便的使用spring-mvc的各种注解来开发http和web服务了。

    客户端注入

    如上述代码,通过@TarsClient(“TarsJavaTest.SpringBootServer.HelloObj”)即可注入HelloWordPrx客户端,如果只填写Obj名称则采用默认值注入客户端,当然你也可以在注解中自定义客户端配置:

    1. @TarsServant("HelloObj")
    2. public class HelloWorldServantImpl implements HelloWordServant {
    3. @TarsClient(name = "TarsJavaTest.SpringBootServer.HelloObj", syncTimeout = 1000)
    4. HelloWordPrx prx;
    5. }

    这样就设置了客户端同步超时时间,该注解提供了所有常用配置的配置项:

    1. @Target({ ElementType.FIELD })
    2. @Retention(RetentionPolicy.RUNTIME)
    3. @Documented
    4. public @interface TarsClient {
    5. @AliasFor("value")
    6. String name() default "";
    7. String setDivision() default "";
    8. boolean isgray() default false;
    9. int connections() default Constants.default_connections;
    10. int connectTimeout() default Constants.default_connect_timeout;
    11. int syncTimeout() default Constants.default_sync_timeout;
    12. int asyncTimeout() default Constants.default_async_timeout;
    13. boolean enableSet() default false;
    14. boolean tcpNoDelay() default false;
    15. String charsetName() default "UTF-8";
    16. }

    包括连接数、同步异步超时时间,字符集等均可以在注解中配置。

    编写完成代码后,可以通过spring boot提供的spring-boot-maven-plugin插件进行打包,将服务打包为jar包后上传即可启动。

    如何在本地启动和开发调试tars

    如需使用tars-spring-boot的新功能需要将tars升级到1.6.1版本及以上版本,本次改动相对较大,附上版本升级指南:

    1. 管理平台需要重新编译升级。
    2. tars-node需要升级到新版本。
    3. 模板选择需要选tars.tarsjava.springboot模版。如果不是重新搭建环境可自行添加模板,父模板选择tars.tarsjava.default,内容如下: