背景
spring boot 3.0使用的spring framework 6.0里有一个全新的http服务调用注解@HttpExchange
,该注解的用途是可以进行申明式http远程服务调用。与Feign作用相同,在spring boot 3.x里,由于本身spring内置,相比Feign可以大幅减少第三方包依赖,且比Feign进轻巧。
依赖:
@HttpExchange
位于spring-web.jar里,因此只要项目是spring boot 3.x且引入了spring-boot-starter-web,即可使用@HttpExchange
进行申明式http远程服务调用。
使用步骤
步骤1:使用@HttpExchange
定义http接口,此类可以打包成独立jar或独立maven module工程,用于给后面的provider和client依赖。
@HttpExchange("/hello")
public interface HelloClient {
@GetExchange("/world")
String world(@RequestParam("world") String world);
@PostExchange("/user")
UserResponse user(@RequestBody UserRequest userRequest);
@Data
class UserRequest {
String userName;
}
@Data
class UserResponse {
String userName;
String remark;
}
}
步骤2:在服务提供工程里(provider)里实现一个以上接口的服务端
@RestController
public class HelloProvider implements HelloClient {
@Override
public String world(String world) {
return "Hello " + world;
}
@Override
public UserResponse user(UserRequest userRequest) {
UserResponse userResponse = new UserResponse();
userResponse.setUserName(userRequest.getUserName());
return userResponse;
}
}
步骤3:在服务调用工程里(client)里配置http远程服务client:
@Configuration
public class HttpClientConfig {
@Bean
RestClient.Builder restClientBuilder() {
return RestClient.builder();
}
@Bean
public HelloClient helloClient(RestClient.Builder restClientBuilder) {
return HttpServiceProxyFactory
.builder()
.exchangeAdapter(
RestClientAdapter.create(
restClientBuilder.baseUrl("http://localhost:8001").build()
)
)
.build().createClient(HelloClient.class);
}
}
步骤4:在服务调用工程里(client)里进行http远程服务调用
@RestController
public class MyClientController {
/**
* 注入远程服务
*/
@Autowired
private HelloClient helloClient;
@GetMapping("/client")
public String client() {
return helloClient.world("this is a client"); // 虽然helloClient的实现不在此工程,但调用时像调本地方法一样简单
}
}
标签:FeignClient,HttpExchange,http,String,spring,world,public
From: https://www.cnblogs.com/jiayuan2006/p/18156919