springMVC get请求及地址的写法,以及eureka服务消费者的调用

1 篇文章 0 订阅

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中的定义的方式相关。

参考文章:https://www.cnblogs.com/wushifeng/p/6142288.html

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值