SpringMVC get请求方式
方式一,传统方式:
后台代码:
@RequestMapping("/animalConsumer")
public Animal getAnimal(@RequestParam(value = "color") String color){
return animalService.getAnimal(color);
}
前端访问路径:http://ip:端口号/animal?color=red
方式二:restful风格
后台代码:
@RequestMapping("/dogConsumer/{color}")
public Animal getDog(@PathVariable(value = "color")String color){
return animalService.getDog(color);
}
前端访问路径:http://ip:端口号/dog/bule
eureka消费者get方式的调用
方式一:传统方式
业务层对服务的调用
@Autowired
private LoadBalancerClient loadBalancerClient;
public Animal getAnimal(String color){
//选择调用服务的名称 ServiceInstance封装了服务的基本信息,如IP,端口等
ServiceInstance si = loadBalancerClient.choose("eureka-provider-animal");
//拼接访问服务的url,形如http://localhost:9092/animal
StringBuffer sb = new StringBuffer();
sb.append("http://").append(si.getHost()).append(":").append(si.getPort()).append("/animal").append("?color="+color);
//SpringMVC RestTemplate
RestTemplate rt = new RestTemplate();
ParameterizedTypeReference<Animal> type = new ParameterizedTypeReference<Animal>() {};
MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
ResponseEntity<Animal> response = rt.exchange(sb.toString(), HttpMethod.GET, null, type);
Animal animal = response.getBody();
return animal;
}
注:get请求方式,传参直接拼接URL
前端访问路径与消费者Controller中定义的方式相关,可以是restful风格,也可以是传统方式,没有影响
方式二:restful风格
public Animal getDog(String color){
ServiceInstance si = loadBalancerClient.choose("eureka-provider-animal");
StringBuffer sb = new StringBuffer();
sb.append("http://").append(si.getHost()).append(":").append(si.getPort()).append("/dog/"+color);
RestTemplate rt = new RestTemplate();
ParameterizedTypeReference<Animal> type = new ParameterizedTypeReference<Animal>() {};
ResponseEntity<Animal> response = rt.exchange(sb.toString(), HttpMethod.GET, null, type);
Animal animal = response.getBody();
return animal;
}
不同点在于对URL的拼接方式不一样,访问路径还是与消费者Controller中的定义的方式相关。