问题:http://127.0.0.1:8010/shares/1 即可访问,然后跨服务去拿到昵称。
String targerUrl = "Http://usercenterprovider/users/{id}";
UserDTO userDTO= this.restTemplate.getForObject(
targerUrl,
UserDTO.class,userId
);
手写一个客户端测负载均衡器(给一个List,选一个元素)
List<ServiceInstance> instances = this.discoveryClient.getInstances("usercenterprovider");
// System.out.println(instances.size());
List<String> targetUrlS= instances.stream().map(instance -> instance.getUri().toString() + "/users/{id}")
.collect(Collectors.toList());
int i = ThreadLocalRandom.current().nextInt(targetUrlS.size());
String targetUrl = targetUrlS.get(i);
log.info("请求的负载均衡的一个实例是:{}",targetUrl);
UserDTO userDTO= this.restTemplate.getForObject(
targetUrl,
UserDTO.class,userId
);
用Robbin如何代替上面这一段代码呢
1、依赖,nacos-discov默认有
2、注解
@Bean
@LoadBalanced //-------------主要是加了这个
public RestTemplate restTemplate(){
return new RestTemplate();
}
3、配置,没有配置
然后改写上面那一段代码:
UserDTO userDTO= this.restTemplate.getForObject(
"http://usercenterprovider/users/{id}",
UserDTO.class,userId
);
-------------------------=----------------------------------
问题:6-6 随机请求负载均衡
@Configuration
@RibbonClient(name = "usercenterprovider",configuration = RibbonConfiguration.class)
public class UserCenterRibbionConfiguration {
}
@Configuration
public class RibbonConfiguration {
// 随机负载均衡
@Bean
public IRule ribbonRule(){
return new RandomRule();
}
}
然后请求http://127.0.0.1:8010/shares/1
发现就是随机的。
问题:如何用配置去代码上面的java代码------属性配置
usercenterprovider:
Ribbon:
NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule
注:其他的属性配置方式:
问题6-11 全局配置负载均衡【@RibbonClient 修改为@RibbonClients,后面的删掉了前半部分,加了一个default】
@Configuration
@RibbonClients(defaultConfiguration = RibbonConfiguration.class)
public class UserCenterRibbionConfiguration {
}
问题:如何去获取实例呢
@Autowired
DiscoveryClient discoveryClient;
List<ServiceInstance> usercenterprovider = this.discoveryClient.getInstances("usercenterprovider");
System.out.println(usercenterprovider.size());