SpringCloud的Ribbon+RestTemplate的三种使用方式分别是什么


SpringCloud的Ribbon+RestTemplate的三种使用方式分别是什么,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。@GetMapping(“getUserList”)public List getUserList(){ RestTemplate template = new RestTemplate(); return template.getForObject(“http://localhost:8080/getUserList”,//List.class);}缺点:1、url硬编码,如果ip有变动,需要在代码中更改
2、如果client为集群,有多个url,该方法只能配一个url;不能使用集群模式方式二:注入LoadBalancerClient ,获得应用名称为providerServcidName(备注:服务提供者名称)的应用的其中一个实例,获得url,再使用RestTemplate获取数据,实现负载均衡@RestControllerpublic class UserController {@Autowired private LoadBalancerClient loadBalancerClient; @GetMapping(“getUserList”) public List getUserList() { RestTempl 香港云主机ate template = new RestTemplate(); // 选择服务实例,根据传入的服务名serviceId, // 从负载均衡器中挑选一个对应服务的实例。
ServiceInstance instance = loadBalancerClient .choose(“providerServcidName“); String url = String.format(“http://%s:%s”, instance.getHost(), instance.getPort() + “/getUserList”); return template.getForObject(url, List.class); }}import org.springframework.cloud.client.loadbalancer.LoadBalanced;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.web.client.RestTemplate;@Configurationpublic class RestTemplateConfig { @Bean @LoadBalanced public RestTemplate restTemplate(){ return new RestTemplate(); }}在controller中注入RestTemplate对象,直接调用getForObject方法,注意url中直接写应用名称,不要写ip:portimport org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RestController;import org.springframework.web.client.RestTemplate;@RestControllerpublic class UserController { @Autowired private RestTemplate restTemplate; @GetMapping(“getUserList”) public String getUserList() { return restTemplate .getForObject(“http://providerServcidName/getUserList”, List.class); }}看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注开发云行业资讯频道,感谢您对开发云的支持。

相关推荐: 电脑出现蓝屏故障怎么办

这篇文章将为大家详细讲解有关电脑出现蓝屏故障怎么办,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。什么是电脑蓝屏?电脑蓝屏,又叫蓝屏死机(Blue Screen of Death,简称BSOD),是微软的Windows系列操作…

免责声明:本站发布的图片视频文字,以转载和分享为主,文章观点不代表本站立场,本站不承担相关法律责任;如果涉及侵权请联系邮箱:360163164@qq.com举报,并提供相关证据,经查实将立刻删除涉嫌侵权内容。

(0)
打赏 微信扫一扫 微信扫一扫
上一篇 08/14 17:00
下一篇 08/14 17:00

相关推荐