SpringCloud(三)Ribbon负载均衡

上篇文章我们成功的将providr和consumer注册到eureka上面了。但是有两个问题:

1、 consumer通过rest请求provider的时候,url是硬编码

return this.restTemplate.getForEntity("http://localhost:8001/simple/" + id, User.class).getBody();

2、 provider怎么做到负载均衡。


解决硬编码问题

上篇文章结尾我们能看到provider在启动并注册到eureka后,eureka会有一行log

  1. Registered instance MICIROSERVICE-PROVIDER/windows10.microdone.cn:miciroservice-provider:8001 with status UP (replication=false
这里的miciroservice-provider是我们定义在provider application.yml里的spring.application.name,这里也代表VIP(虚拟ip),也就是consumer可以通过这个IP去访问provider的应用例如:http://miciroservice-provider/simple/2 == http://localhost:8001/simple/2 
所以我们只需要将上面的访问url改成对应的虚拟IP就可以了。
return this.restTemplate.getForEntity("http://miciroservice-provider/simple/" + id, User.class).getBody()

负载均衡

本篇文章使用ribbon实现负载均衡,很简单,一句话。



package com.zhuyang.cloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
@EnableDiscoveryClient
public class DemoMicroserviceConsumerUserApplication {
	@Bean
	@LoadBalanced //ribbon
	public RestTemplate restTemplate() {  // equals to RestTemplate restTemplate = new RestTemplate()
		return new RestTemplate();
	}

	public static void main(String[] args) {
		SpringApplication.run(DemoMicroserviceConsumerUserApplication.class, args);
	}
}
为了测试,我们可以启动两个provider实例(注意:port不一样),然后多次访问consumer,正常情况下两个provider应该都会命中到,而且次数应该一样,因为默认是轮询的方式。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值