Java 杂谈Java学习笔记我爱编程

Spring Cloud(七):Zuul

2018-04-03  本文已影响43人  聪明的奇瑞

Ribbon 简介

Ribbon

快速入门-服务消费者整合 Ribbon

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-ribbobn</artifactId>
</dependency>
@Bean
@LoadBalanced
public RestTemplate restTemplate(){
    return new RestTemplate();
}
@RestController
public class MovieController {
    private final Logger log = LoggerFactory.getLogger(MovieController.class);

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @GetMapping("/user/{id}")
    public UserEntity findById(@PathVariable int id){
        return this.restTemplate.getForObject("http://film-user/"+id,UserEntity.class);
    }

    @GetMapping("/log-instance")
    public void logInstance(){
        ServiceInstance serviceInstance = this.loadBalancerClient.choose("film-user");
        log.info("{}:{}:{}",serviceInstance.getServiceId(),serviceInstance.getHost(),serviceInstance.getPort());
    }
}

配置 Ribbon

代码方式

/**
 * 该类为配置类
 * 不应该被ComponentScan扫描
 */
@Configuration
public class RibbonConfiguration {
    @Bean
    public IRule ribbonRule(){
        //配置负载均衡的规则,更改为随机
        return new RandomRule();
    }
}

@SpringBootApplication
@EnableDiscoveryClient
@RibbonClient(name = "flim-user",configuration = RibbonConfiguration.class)
public class FlimConsumerApplication {
    @Bean
    @LoadBalanced
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
    public static void main(String[] args) {
        SpringApplication.run(FlimConsumerApplication.class, args);
    }
}
2017-12-17 21:08:52.769  INFO 12524 --- [nio-8010-exec-7] com.linyuan.controller.MovieController   : flim-user:linyuandembp:8763
2017-12-17 21:08:52.946  INFO 12524 --- [nio-8010-exec-8] com.linyuan.controller.MovieController   : flim-user:linyuandembp:8763
2017-12-17 21:08:53.138  INFO 12524 --- [nio-8010-exec-9] com.linyuan.controller.MovieController   : flim-user:linyuandembp:8763
2017-12-17 21:08:53.319  INFO 12524 --- [io-8010-exec-10] com.linyuan.controller.MovieController   : flim-user:linyuandembp:8764
2017-12-17 21:08:53.511  INFO 12524 --- [nio-8010-exec-1] com.linyuan.controller.MovieController   : flim-user:linyuandembp:8763

配置文件方式

flim-user:
  ribbon:
    NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule
ribbon:
    ConnectionTimeout: #连接超时时间
    ReadTimeout: #读取超时时间
    OkToRetryOnAllOperatotions: #对所有操作请求都进行重试
    MaxAutoRetriesNextServer:  #切换服务器实例的重试次数
    MaxAutoRetries:   #对当前实例的重试次数
    ServerListRefreshInterval:   #刷新服务列表源的间隔时间
上一篇 下一篇

猜你喜欢

热点阅读