原理
Spring的HTTP 服务接口是一个带有@HttpExchange方法的 Java 接口,它支持的支持的注解类型有:
- @HttpExchange:是用于指定 HTTP 端点的通用注释。在接口级别使用时,它适用于所有方法。
- @GetExchange:为 HTTP GET请求指定@HttpExchange。
- @PostExchange:为 HTTP POST请求指定@HttpExchange。
- @PutExchange:为 HTTP PUT请求指定@HttpExchange。
- @DeleteExchange:为 HTTP DELETE请求指定@HttpExchange。
- @PatchExchange:为 HTTP PATCH请求指定@HttpExchange。
示例:访问远程接口https://api.chucknorris.io/jokes/random
第一步:添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
第二步:配置类
@Configuration
public class HttpConfig {
@Bean
public WebClient webClient() {
return WebClient.builder()
.baseUrl("https://api.chucknorris.io/")
.build();
}
@Bean
public ChuckNorrisService postClient(WebClient webClient) {
HttpServiceProxyFactory httpServiceProxyFactory =
HttpServiceProxyFactory.builder(WebClientAdapter.forClient(webClient))
.build();
return httpServiceProxyFactory.createClient(ChuckNorrisService.class);
}
}
第三步:远程Service
@HttpExchange(url = "/jokes")
public interface ChuckNorrisService {
//https://api.chucknorris.io/jokes/random
@HttpExchange(url = "/random", method = "GET")
//@GetExchange("/reduct")
String reduct();
}
第四步:Controller中使用远程Service
@RestController
@RequestMapping("/order")
public class OrderController {
@Resource
private ChuckNorrisService chuckNorrisService;
@GetMapping("/create")
public String create() {
System.out.println("下单成功!");
//扣除库存
String stockMsg = chuckNorrisService.reduct();
return "order add success -- " + stockMsg;
}
}