Tiven Wang
Wang Tiven August 04, 2017
425 favorite favorites
bookmark bookmark
share share

基於上一篇Microservices - Restful API HATEOAS介紹了支持 HATEOAS 特性的 Restful API,本篇介紹如何調用這樣的 Restful APIs,即 consumer client 端的代碼編寫。 Template method pattern

下載本文完整項目代碼 Github

Dependency

我們使用 spring web 裡的 RestTemplate 去調用 Restful API,所以在 Spring Boot Maven 項目裡只需要添加這個依賴包

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
</dependency>

Create Client

創建一個新的類英雄管理者 HeroManager 來作為客戶端調用英雄的 Restful APIs

@Component
public class HeroManager implements CommandLineRunner {

	public static String BASE_URL = "http://localhost";

	@Value("${server.port}")
	public String serverPort;

	private final RestTemplate template = new RestTemplate();

	@Override
	public void run(String... args) throws Exception {

		String heroUrl = BASE_URL + ":" + serverPort + "/hero";

		Hero batman = new Hero("Batman");

		BigInteger id = template.postForObject(heroUrl, batman, BigInteger.class);

		HeroResource hero = template.getForObject(heroUrl + "/{hero}", HeroResource.class, id);

		System.out.println("Got you " + hero.getName());
	}

}

Test

本地創建一個 MongoDB 服務

docker run --rm --name my-mongo -d -p 27017:27017 mongo

啟動應用程序

mvn spring-boot:run

可以在後台看到打印出的信息

...
2017-08-04 17:31:32.961  INFO 16292 --- [nio-8090-exec-1] org.mongodb.driver.connection            : Opened connection [connectionId{localValue:2, serverValue:7}] to localhost:27017
Got you Batman
2017-08-04 17:31:33.169  INFO 16292 --- [           main] wang.tiven.trycf.HeroApplication         : Started HeroApplication in 9.013 seconds (JVM running for 14.152)

Authentication

Exception

References

Similar Posts

  • Microservices - Inter-Process Communication The kernal of Microservices Architecture is inter-process communication
  • Microservices - API Gateway : Spring Cloud Gateway Spring Cloud Gateway 是一个新的基于 Spring Framework 5, Project Reactor and Spring Boot 2.0 的 API Gateway 产品
  • Microservices - API Gateway : Zuul Zuul 是来自 NetFlix 的 Microservice 产品家族的 API Gateway 服务或者说是 edge 服务。 Zuul 为开发者构建微服务架构提供了 Routing,Monitoring,Managing resiliency,Security等功能。简单来说,Zuul 可以被看作是一个反向代理,在服务实例间 Zuul 代理内部使用 Eureka server 作为 service discovery,使用Ribbon 作为 load balancing
  • Microservices - Transactions
  • Microservices - API Gateway Implement an API gateway that is the single entry point for all clients. The API gateway handles requests in one of two ways. Some requests are simply proxied/routed to the appropriate service. It handles other requests by fanning out to multiple services.
  • Microservices - Circuit Breaker 访问远程服务时, 比依赖超时时间更好一些的方式是一种叫断路器(Circuit Breaker)的模式. Circuit Breaker 就像一位交通警察, 在前方道路畅通的情况下, 他会放行; 当前方道路由于各种原因拥堵时, 他会告诉你前方道路不通请回; 如果他是个更智能的交警的话, 还会告诉你前方道路部分拥堵, 只允许部分车辆通过, 比如实行单双号.

Comments

Back to Top