007--Eureka和Ribbon

2018-05-08  本文已影响14人  糖纸疯了

SpringCloud官网

1、主题:如何在Eureka上使用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);
        }
    }
    @GetMapping("/movie/{id}")
    public User findById(@PathVariable Long id) {
      return this.restTemplate.getForObject("http://server-provider/simple/" + id, User.class);
    }   

2、主题:如何在Eureka上使用Ribbon限定负载的服务

    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配置

      ribbon:
        NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule
    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
上一篇下一篇

猜你喜欢

热点阅读