在SpringBoot3版本发布后 官方便声明了推荐使用了内置声明式的HTTP客户端。
一、声明式HTTP客户端使用(依赖引入)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
二、被调用方编写(粗略代码逻辑)
@RestController
public class UserController {
@GetMapping("/users")
public List<User> list() {
//返回十条数据 从1开始到10 输出示例:1:User1 --- 10:User10
return IntStream.rangeClosed(1, 10)
.mapToObj(i -> new User(i, "User" + i))
.collect(Collectors.toList());
}
}
三、调用方 HTTP端点编写
//标记为http interface端点
@HttpExchange
public interface UserApiService {
//被调用方的接口路径
@GetExchange("/users")
List<User> getUsers();
}
四、 工具类封装
public class RemoteUtil {
/**
* 远程调用方法 模板代码
* @param url 调用的地址
* @param serviceType 返回的类型
*/
public static <S> S Remoting(String url, Class<S> serviceType){
WebClient client = WebClient.builder().baseUrl(url).build();
HttpServiceProxyFactory factory = HttpServiceProxyFactory.builder(WebClientAdapter.forClient(client)).build();
return factory.createClient(serviceType);
}
}
五、调用地址定义常量
public class UserConstant {
public static final String USER_SERVICE_ADDRESS = "http://localhost:8080";
}
六、业务调用代码编写
@Service
public class UserServiceImpl implements UserService{
@Override
public List<User> getUsers() {
UserApiService userApiService = RemoteUtil.Remoting(UserConstant.USER_SERVICE_ADDRESS, UserApiService.class);
return userApiService.getUsers();
}
}
七、调用接口
@RestController
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/getUsers")
public List<User> getUsers(){
return userService.getUsers();
}
}