-
什么是客户端负载均衡
我们一般讲的负载均衡都是服务端的负载均衡,比如硬件负载均衡F5,软件负载均衡 Nginx. 什么是客户端的负载均衡呢?和服务端负载均衡的最大不同,是维护自己要访问的服务端清单所存储的位置
RibbonEurekaAutoConfiguration
-
利用Ribbon实现负载均衡的步骤
- 服务提供者启动多个服务实例
- 服务消费者调用被
@LoadBalanced
注解过的RestTemplate
@Bean
@LoadBalanced
RestTemplate restTemplate() {
return new RestTemplate();
}
-
RestTemplate 用法详解
-
GET请求
-
getForEntity
@Autowired
RestTemplate restTemplate;
@RequestMapping(value="/ribbon-consumer1",method = RequestMethod.GET)
public String helloConsumer1() {
return restTemplate.getForEntity("http://HELLO-SERVICE/hello", String.class).getBody();
}
-
getForObject
@RequestMapping(value="/getUser",method = RequestMethod.GET)
public User getUser() {
ResponseEntity<User> responseEntity= restTemplate.getForEntity("http://HELLO-SERVICE/getUser", User.class);
User body = responseEntity.getBody();
return body;
}
有参数传递
@RequestMapping(value="/getUserObject",method = RequestMethod.GET)
public User getUserObject() {
User responseEntity= restTemplate.getForObject("http://HELLO-SERVICE/getUser?name={1}", User.class,"zzj");
return responseEntity;
}
通过Map对象封装参数
@RequestMapping(value="/getUserByMap",method = RequestMethod.GET)
public User getUserByMap() {
Map<String,String> map =new HashMap<>();
map.put("name", "zzj");
User responseEntity= restTemplate.getForObject("http://HELLO-SERVICE/getUser?name={name}", User.class,map);
return responseEntity;
}
-
POST请求
POST和GET一样,有postForEntity和postForObject方法,参数大致相同
@RequestMapping(value="/user",method = RequestMethod.POST)
public boolean save() {
User user = new User();
user.setName("abc");
user.setAge(111);
return restTemplate.postForObject("http://HELLO-SERVICE/user", user, boolean.class);
}
postForLocation
返回URI
-
PUT请求
-
DELETE请求
-
exchange 方法
该方法返回的是一个 ResponseEntity<T>
其中有个参数是传入 HttpEntity
,HttpEntity
是对请求的封装,包含请求头header和请求体body.
网友评论