iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 21
0
Software Development

30天從零開始 使用 Spring Boot 跟 Spring Cloud 建構完整微服務架構系列 第 21

Day 21 - 呼叫遠端服務 Feign

增加 LoadBalance 機制

修改 reservation-client 專案

先把依賴 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"
]

上一篇
Day 20 - Gateway Zuul
下一篇
Day 22 - 遠端服務機制 Ribbon
系列文
30天從零開始 使用 Spring Boot 跟 Spring Cloud 建構完整微服務架構35
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言