## 六、RestTemplate
### 6.1 RestTemplate 规范
在使用 RestTemplate 调用对应 RESTful 接口时候,使用的方法应该与接口声明方式(@GetMapping、@PostMapping、@PutMapping、@DeleteMapping)保持一致。其对应关系如下:
- GET 请求 ( getForObject 、getForEntity )
- POST 请求( postForObject 、postForEntity)
- PUT 请求( put )
- DELETE 请求 ( delete )
### 6.2 ForEntity 和 ForObject 的区别
- `ForEntity()` 发送一个请求,返回的 ResponseEntity 包含了响应体所映射成的对象,
- `ForObject()` 发送一个请求,返回的请求体将映射为一个对象。示例如下:
```java
ResponseEntity responseEntity = restTemplate.getForEntity("http://producer/product/{1}", Product.class, id);
Product product = restTemplate.getForObject("http://producer/product/{1}", Product.class, id);
```
## 七、负载均衡策略
Ribbon 内置了多种负载均衡策略,如果有更复杂的需求,可以自己实现 IRule。
### 7.1 内置的负载均衡的策略

图片来源于博客:[Ribbon 负载均衡策略与自定义配置](https://blog.csdn.net/jrn1012/article/details/77837680)
### 7.2 指定负载均衡的策略
可以通过两种方式来为服务指定具体的负载均衡的策略,分别是基于配置的方式和基于代码的方式:
**1. 基于配置的方式**
如下将为名为 `user` 的服务设置其负载均衡的策略为 WeightedResponseTimeRule :
```yaml
users:
ribbon:
NFLoadBalancerRuleClassName: com.netflix.loadbalancer.WeightedResponseTimeRule
```
**2. 基于代码的方式**
```java
@Configuration
@RibbonClient(name = "custom", configuration = CustomConfiguration.class)
public class TestConfiguration {
}
```
```java
@Configuration
public class CustomConfiguration {
@Bean
public IRule ribbonRule() {
return new BestAvailableRule();
}
}
```
在使用代码方式时, [官方文档](http://cloud.spring.io/spring-cloud-netflix/multi/multi_spring-cloud-ribbon.html#_customizing_the_ribbon_client) 中有以下强调说明:
```
The CustomConfiguration clas must be a @Configuration class, but take care that it is not in a @ComponentScan for the main application context. Otherwise, it is shared by all the @RibbonClients. If you use @ComponentScan (or @SpringBootApplication), you need to take steps to avoid it being included (for instance, you can put it in a separate, non-overlapping package or specify the packages to scan explicitly in the @ComponentScan).
```
CustomConfiguration 类必须使用 @Configuration 进行注解,但需要注意的它不能在 @ComponentScan 主应用程序的上下文。否则,它将被所有 @RibbonClients 共享。如果你使用 @ComponentScan(或 @SpringBootApplication),你需要采取一些措施来避免它被扫描到(例如,你可以把它放在一个独立的,非重叠的包,或用 @ComponentScan 时显示扫描指定的包,从而避开扫描到 CustomConfiguration 所在的包)。