在Spring Cloud中使用
依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>
- spring-cloud-starter-netflix-eureka-client 注册该服务到Eureka注册中心
- spring-cloud-starter-netflix-ribbon 让客户端支持负载均衡
配置RestTemplate
@Bean
@LoadBalanced
RestTemplate restTemplate() {
return new RestTemplate();
}
@LoadBalanced注解让RestTemplate支持负载均衡
使用RestTemplate请求微服务
假定有一个已启动的微服务:HELLO-SERVICE
Get请求
restTemplate url参数映射方式一:
String body = restTemplate.getForEntity("http://HELLO-SERVICE/hello1?name={1}", String.class, "restTemplate url参数映射方式一").getBody();
restTemplate url参数映射方式二:
Map<String, String> params = new HashMap<>();
params.put("name", "restTemplate url参数映射方式二");
String body = restTemplate.getForEntity("http://HELLO-SERVICE/hello1?name={name}", String.class, params).getBody();
restTemplate url参数映射方式三:
UriComponents uriComponents = UriComponentsBuilder.fromUriString("http://HELLO-SERVICE/hello1?name={name}")
.build()
.expand("yidasanqian expand")
.encode();
URI uri = uriComponents.toUri();
String body = restTemplate.getForEntity(uri, String.class).getBody();
Post请求
String postResult = restTemplate.postForObject("http://HELLO-SERVICE/hello3", user, String.class);
ResponseEntity<String> responseEntity = restTemplate.postForEntity("http://HELLO-SERVICE/hello3", user, String.class);
postForObject
和postForEntity
方法的第二个参数是一个请求体,第三个参数是响应结果类型。
Put请求
restTemplate.put("http://HELLO-SERVICE/hello4?name={1}", user, "yidasanqian");
Delete请求
restTemplate.delete("http://HELLO-SERVICE/hello6?id={1}", "1");
Patch请求
String result = restTemplate.patchForObject("http://HELLO-SERVICE/hello5", user, String.class);