SpringCloud官网
1、主题:如何在Eureka上使用Ribbon客户端负载均衡
- 1.首先注册Ribbon-start,但是因为有Eureka-start的实现,已经包含了Ribbon,无需重复导入
- 2.然后添加Ribbon注解,因为是客户端负载(加在消费者上面)
@SpringBootApplication
@EnableEurekaClient
public class ServerConsumeRibbonApplication {
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(ServerConsumeRibbonApplication.class, args);
}
}
- 3.然后去验证我们的想法-->如何用Eclipse模拟多个服务提供者
因为要调用“多个相同的负载提供者”,所以必须使用VIP(虚拟IP地址)
@GetMapping("/movie/{id}")
public User findById(@PathVariable Long id) {
return this.restTemplate.getForObject("http://server-provider/simple/" + id, User.class);
}
- 4.然后用Eclipse模拟多个服务提供者
- 4.1 点击Run-->Run Configuration-->起一个名字+选一个主程序(然后Close,不要点击RUN)
- 4.2 然后找到项目,更改掉里面的端口配置
- 4.3 点击Run-->找到刚才设定的项目,点击启动即可
2、主题:如何在Eureka上使用Ribbon限定负载的服务
- 1.最简单的做法,将Ribbon的配置方法类不要放入Application的统计目录下/子包
- 2.指定扫描包的配置
2.1 创建ExcludeFromComponentScan借口标注
public @interface ExcludeFromComponentScan {
}
2.2 将标注添加到我们的Ribbon上面
@Configuration
@ExcludeFromComponentScan
public class TestConfiguration {
@Bean
public IRule ribbonRule() {
return new RandomRule();
}
}
3.在主文件目录上添加
@SpringBootApplication
@EnableEurekaClient
@RibbonClient(name = "microservice-provider-user", configuration = TestConfiguration.class)
@ComponentScan(excludeFilters = { @ComponentScan.Filter(type = FilterType.ANNOTATION, value = ExcludeFromComponentScan.class) })
public class ConsumerMovieRibbonApplication {
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(ConsumerMovieRibbonApplication.class, args);
}
}
4.重启即可:
1.因为@ExcludeFromComponentScan标记在TestConfiguration上面
2.因为@RibbonClient指定了请求的“服务名”
3.在负载的时候,只有被标识的服务才会进行负载
3、主题:如何在Eureka上使用Ribbon使用property配置
- 1.使用Ribbon使用property配置,只需要在property(yml)上添加microservice-provider-user:
ribbon:
NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule
- 2.Eureka中默认的region配置
点击yml中的eureka.client.serviceUrl,然后在源码中搜索就会看到
this.region = "us-east-1";//即使eureka.client.serviceUrl.region的默认配置
4、主题:怎么单独的使用Ribbon而不使用Eureka
1.使用了Eureka,但在使用Ribbon时候不使用Eureka
2.没有Eureka,如何使用Ribbon
Example: Disable Eureka use in Ribbon
Setting the property ribbon.eureka.enabled = false will explicitly disable the use of Eureka in Ribbon.
---- 使用实例如下:
application.yml
ribbon:
eureka:
enabled: false
Example: How to Use Ribbon Without Eureka
Eureka is a convenient way to abstract the discovery of remote servers so you don’t have to hard code their URLs in clients, but if you prefer not to use it, Ribbon and Feign are still quite amenable. Suppose you have declared a @RibbonClient for "stores", and Eureka is not in use (and not even on the classpath). The Ribbon client defaults to a configured server list, and you can supply the configuration like this
---- 使用实例如下:
application.yml
stores:
ribbon:
listOfServers: example.com,google.com