前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >SpringCloud的Ribbon+RestTemplate的三种使用方式

SpringCloud的Ribbon+RestTemplate的三种使用方式

作者头像
BUG弄潮儿
发布2022-06-30 16:21:41
3690
发布2022-06-30 16:21:41
举报
文章被收录于专栏:JAVA乐园

方式一:直接使用new实例化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获取数据,实现负载均衡

@RestController

public class UserController {

@Autowired

private LoadBalancerClient loadBalancerClient;

@GetMapping("getUserList")

public List getUserList() {

RestTemplate 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);

}

}

方式三:RestTemplate通过配置注入Spring容器来使用

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;

@Configuration

public class RestTemplateConfig {

@Bean

@LoadBalanced

public RestTemplate restTemplate(){

return new RestTemplate();

}

}

在controller中注入RestTemplate对象,直接调用getForObject方法,注意url中直接写应用名称,不要写ip:port

import 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;

@RestController

public class UserController {

@Autowired

private RestTemplate restTemplate;

@GetMapping("getUserList")

public String getUserList() {

return restTemplate

.getForObject("http://providerServcidName/getUserList", List.class);

}

}

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2018-08-22,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 BUG弄潮儿 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 方式一:直接使用new实例化RestTemplate对象
  • 方式三:RestTemplate通过配置注入Spring容器来使用
相关产品与服务
负载均衡
负载均衡(Cloud Load Balancer,CLB)提供安全快捷的流量分发服务,访问流量经由 CLB 可以自动分配到云中的多台后端服务器上,扩展系统的服务能力并消除单点故障。负载均衡支持亿级连接和千万级并发,可轻松应对大流量访问,满足业务需求。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档