retrofit框架的使用总结

144 阅读1分钟

为什么会使用retrofit

解决模块之间需要相互引入依赖的问题,如果项目后期需要考虑从springboot项目迁移到springcloud的话,那么久需要提前进行规划

正常流程

描述

新创建一个mavenTest02工程,作为父工程,父工程下面有test01,test02模块

image.png

如果test02需要使用test01模块里面的方法,一般是直接在test02的pom里面引入test01,这样模块多了之后,会导致不好拆分,很不便于转化成微服务项目,因此可以引入retrofit框架,把原本服务间的强依赖进行拆分,改成用服务调用的方式

具体实现

依赖

1.在父工程mavenTest2里面引入依赖

<dependency>
    <groupId>com.github.lianjiatech</groupId>
    <artifactId>retrofit-spring-boot-starter</artifactId>
    <version>2.3.9</version>
</dependency>

服务提供方

@RestController
@RequiredArgsConstructor
public class Test01Controller {

    private final StudentServiceImpl studentService;

    @GetMapping("/test01")
    public String test01() {
        studentService.stuMethod();
        return "test01";
    }
}

里面就是调用了service的stuMethod()方法

服务调用方

  1. 接口
@RetrofitClient(baseUrl = "http://localhost:8083")
@Component
public interface HttpApi {

    @GET("test01")
    String invokeStuMethod();
}
  1. 具体使用
@RequiredArgsConstructor
@Service
public class Test2ServiceImpl {
    private final HttpApi httpApi;
    
    public void method02() {
        val s = httpApi.invokeStuMethod();
    }
}

注意点

// TODO 待完善
  1. 在服务调用的时候,正常的前后端分离项目都会有token,这个时候需要把token也设置上
  2. 对于作为公共参数的DTO。可以放到common模块里面,让test01和test02都引入这个依赖