SpringBoot中远程调用HTTP接口有很多种现成的方案,比如:RestTemplate、RestClient、WebClient等,以及SpringCloud中经常用到的一个非常好用的组件Openfeign。现在在4.0中再也不用羡慕Openfeign了,因为4.0也提供了类似于Openfeign的声明式远程调用客户端Http Service Interface Client。
快速入门
使用起来非常简单那,总共就3步:
- 定义接口
- 导入接口
- 使用接口
比如现在已经有一个商品服务GoodsService:
java
@RestController
@RequestMapping("/api/goods/")
public class GoodsController {
@GetMapping("/{goodsId}")
Goods getById(@PathVariable("goodsId")Integer goodsId){
return new Goods(goodsId);
}
record Goods(Integer id){}
}
如何对里面的接口进行远程调用呢?
定义接口
java
@HttpExchange(url = "http://localhost:8082/api/goods")
public interface GoodsApi {
@GetExchange(url="/{goodsId}")
Goods getById(@PathVariable("goodsId")Integer goodsId);
record Goods(Integer id){}
}
HttpExchange: 对应于RequestMapping,说明这个是Rest客户端, url可以设置服务的地址,当然base-url部分也可以用其他方式来指定,稍后会说明GetExchange:对应GetMapping,说明这个是GET请求,聪明的你一定可以想到还会有对应的PostExchange、PutExchange、DeleteExchange等。PathVariable:就是路径参数,传参这一部分跟Controller的传参是一模一样的。
导入接口
java
@SpringBootApplication
@ImportHttpServices(basePackages = "com.github.xjs.client", types = GoodsApi.class)
public class ClientApplication {
public static void main(String[] args) {
SpringApplication.run(ClientApplication.class, args);
}
}
ImportHttpServices:用来把接口注入到Spring容器,其中:basePackages:是做包扫描,这个包下面所有的接口都会被当成是Rest客户端types: 可以显示指定一个或者多个Rest客户端- 二者选其中任何一个就可以
使用接口
跟使用一个普通的bean没有任何区别:
java
@RestController
@RequestMapping("/api/client/")
public class ClientController {
//注入bean
@Autowired
private GoodsApi goodsApi;
@GetMapping("/goods/{goodsId}")
public GoodsApi.Goods getById(@PathVariable("goodsId")Integer goodsId){
//直接调用接口
return goodsApi.getById(goodsId);
}
}
就是这么简单!简直爽的飞起!
上面的案例中我们硬编码了服务的绝对地址,在实际的开发中一般是在配置文件中进行配置的,那应该如何进行配置呢?请参考:SpringBoot4.0新特性-声明式Rest客户端