先把依賴 hateoas 加回去
build.gradle
dependencies {
compile('org.springframework.boot:spring-boot-starter-actuator')
compile('org.springframework.cloud:spring-cloud-starter-config')
compile('org.springframework.cloud:spring-cloud-starter-eureka')
compile('org.springframework.cloud:spring-cloud-starter-hystrix')
compile('org.springframework.boot:spring-boot-starter-hateoas')
compile('org.springframework.cloud:spring-cloud-starter-stream-redis')
compile('org.springframework.cloud:spring-cloud-starter-zuul')
testCompile('org.springframework.boot:spring-boot-starter-test')
}
然後新增一個控制器 重點在這個 @LoadBalanced
@RestController
@RequestMapping("/reservations")
class ReservationApiGatewayRestController{
@Autowired
@LoadBalanced
private RestTemplate restTemplate;
@RequestMapping("names")
public Collection<String> getReservationNames(){
ParameterizedTypeReference<Resources<Reservation>> ptr =
new ParameterizedTypeReference<Resources<Reservation>>(){};
ResponseEntity<Resources<Reservation>> responseEntity =
this.restTemplate.exchange("http://reservation-service/reservations",
HttpMethod.GET, null, ptr);
Collection<String> nameList = responseEntity
.getBody()
.getContent()
.stream()
.map(Reservation::getReservationName)
.collect(Collectors.toList());
return nameList;
}
}
這邊其實猜得出來它的使用方式,然後下面的部分是Java8的語法喔。
再啟動後從 http://localhost:8050/reservations/names 嘗試抓取資料,結果是可以取得預期的姓名清單
[
"Dr. rod",
"Dr. Syer",
"Juergen",
"ALL THE COMMUNITY",
"Josh"
]