Retrofit 是一款類型安全的 HTTP 客戶端,基於註解聲明 API 接口,自動處理 JSON 序列化/反序列化與網絡請求。本文演示在 Spring Boot 微服務架構中,如何使用 Retrofit 1.9.x 進行服務間調用。
@RestController
@RequestMapping("/hotel")
@Api("HotelController 相關 API")
public class HotelController {
@ApiOperation("獲取酒店信息:Query 參數")
@GetMapping("/getHotelWithQueryParameter")
public Hotel getHotelWithQueryParameter(@RequestParam("hotelname") String hotelname) {
if ("nana".equals(hotelname)) return new Hotel(777, "假日酒店");
return new Hotel(1314, "玫瑰酒店");
}
@ApiOperation("獲取酒店列表:POST 無參")
@PostMapping("/getHotelList")
public List<Hotel> getHotelList() {
return Arrays.asList(new Hotel(1314, "玫瑰酒店"), new Hotel(2046, "2046酒店"));
}
@ApiOperation("獲取酒店列表:POST 帶 Body")
@PostMapping("/getHotelListWithBody")
public List<Hotel> getHotelListWithBody(@RequestBody Hotel hotel) {
List<Hotel> list = new ArrayList<>();
if ("武林酒店".equals(hotel.getHotelname())) {
list.add(new Hotel(13141, "玫瑰酒店1"));
list.add(new Hotel(20461, "2046酒店1"));
return list;
}
list.add(new Hotel(1314, "玫瑰酒店"));
list.add(new Hotel(2046, "2046酒店"));
return list;
}
}
<dependency>
<groupId>com.squareup.retrofit</groupId>
<artifactId>retrofit</artifactId>
<version>1.9.0</version>
</dependency>
@Configuration
public class RestAdapterConfig {
@Bean
public RestAdapter getRestAdapter() {
return new RestAdapter.Builder()
.setEndpoint("https://localhost:8081") // 必須包含協議頭
.build();
}
}
public interface HotelAPI {
@GET("/hotel/getHotelWithQueryParameter")
Hotel getHotelWithQueryParameter(@Query("hotelname") String hotelname);
@POST("/hotel/getHotelList")
List<Hotel> getHotelList();
@POST("/hotel/getHotelListWithBody")
List<Hotel> getHotelListWithBody(@Body Hotel hotel);
}
@Configuration
public class HotelAPIConfig {
@Autowired
private RestAdapter adapter;
@Bean
public HotelAPI getHotelAPI() {
return adapter.create(HotelAPI.class);
}
}
@Service
public class UserService {
@Autowired
private HotelAPI hotelApi;
public Hotel getHotelWithQuery(String name) {
return hotelApi.getHotelWithQueryParameter(name);
}
// 其他方法省略
}
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/getHotelWithQueryParameter")
public Hotel getHotel(@RequestParam("hotelname") String name) {
return userService.getHotelWithQuery(name);
}
// 其他端點省略
}
https://localhost:8081/swagger-ui.html 確認服務正常https://localhost:8080/swagger-ui.html 測試調用鏈路注意: Retrofit 1.x 與 2.x 差異較大,本文基於 1.9.0 版本。生產環境建議升級至 Retrofit 2.x 並搭配 OkHttp。

