Springboot提供外部接口和访问外部接口的简单例子
1. 创建Spring Boot控制器
首先,我们将创建一个Spring Boot控制器来提供API接口。
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api")
public class UserController {
// 假设这里有一个服务来获取用户信息,这里使用模拟数据代替
private final UserService userService = new UserService();
@GetMapping("/user")
public ResponseEntity<?> getUserByMemberNumAndTel(@RequestParam String memberNum, @RequestParam String tel) {
if (memberNum == null || tel == null || memberNum.trim().isEmpty() || tel.trim().isEmpty()) {
return ResponseEntity.badRequest().body("Invalid request: memberNum and tel are required");
}
User user = userService.findUserByMemberNumAndTel(memberNum, tel);
if (user == null) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("User not found");
}
return ResponseEntity.ok().body(new UserResponse(user.getUsername(), user.getEmail(), user.getAddress()));
}
用户实体类
private static class User {
private String username;
private String email;
private String address;
public User(String username, String email, String address) {
this.username = username;
this.email = email;
this.address = address;
}
// Getters and setters
public String getUsername() { return username; }
public String getEmail() { return email; }
public String getAddress() { return address; }
}
用户响应类
private static class UserResponse {
private final String username;
private final String email;
private final String address;
public UserResponse(String username, String email, String address) {
this.username = username;
this.email = email;
this.address = address;
}
// Getters
public String getUsername() { return username; }
public String getEmail() { return email; }
public String getAddress() { return address; }
}
服务接口
private interface UserService {
User findUserByMemberNumAndTel(String memberNum, String tel);
}
服务实现类
private static class UserServiceImpl implements UserService {
@Override
public User findUserByMemberNumAndTel(String memberNum, String tel) {
// 这里应该是数据库查询逻辑,这里使用模拟数据
if ("123456".equals(memberNum) && "1234567890".equals(tel)) {
return new User("John Doe", "john.doe@example.com", "123 Main St");
}
return null;
}
}
}
2. 编写访问API的方法
我们将编写一个方法来调用这个API,并处理返回的响应。如果访问超时(30秒),将抛出访问超时的错误。
import org.springframework.web.client.RestTemplate;
import org.springframework.web.client.ResourceAccessException;
public class ApiClient {
private final RestTemplate restTemplate;
public ApiClient() {
this.restTemplate = new RestTemplate();
// 设置超时时间为30秒
restTemplate.setRequestFactory(new SimpleClientHttpRequestFactory() {{
setConnectTimeout(30000);
setReadTimeout(30000);
}});
}
public UserResponse getUserByMemberNumAndTel(String memberNum, String tel) {
try {
ResponseEntity<UserResponse> response = restTemplate.getForEntity(
"http://localhost:8080/api/user?memberNum={memberNum}&tel={tel}",
UserResponse.class,
memberNum,
tel
);
if (response.getStatusCode() == HttpStatus.OK) {
return response.getBody();
} else if (response.getStatusCode() == HttpStatus.BAD_REQUEST) {
throw new IllegalArgumentException("Invalid request: " + response.getBody());
} else if (response.getStatusCode() == HttpStatus.NOT_FOUND) {
throw new RuntimeException("User not found");
}
} catch (ResourceAccessException e) {
throw new RuntimeException("访问超时,请稍后再试", e);
}
return null;
}
public static void main(String[] args) {
ApiClient apiClient = new ApiClient();
try {
UserResponse userResponse = apiClient.getUserByMemberNumAndTel("123456", "1234567890");
if (userResponse != null) {
System.out.println("User Info:");
System.out.println("Username: " + userResponse.getUsername());
System.out.println("Email: " + userResponse.getEmail());
System.out.println("Address: " + userResponse.getAddress());
} else {
System.out.println("Failed to retrieve user info.");
}
} catch (RuntimeException e) {
System.out.println(e.getMessage());
}
}
}
在这个例子中,ApiClient
类有一个方法getUserByMemberNumAndTel
,它使用RestTemplate
来调用我们之前创建的API。这个方法接受会员账号和电话作为参数,然后发送GET请求到API端点。根据响应的状态码,它将返回用户信息或者抛出异常。
我们设置了RestTemplate
的连接超时和读取超时时间为30秒。如果在30秒内没有收到响应,RestTemplate
将抛出ResourceAccessException
异常,我们捕获这个异常并抛出一个自定义的RuntimeException
,提示用户访问超时。
请注意,你需要根据你的实际环境调整RestTemplate
的URL,以及处理异常和错误响应的逻辑。这个例子中的main
方法是一个简单的测试,用于演示如何调用getUserByMemberNumAndTel
方法并打印用户信息。