zoukankan      html  css  js  c++  java
  • springcloud-ribbon的使用

    在ribbon的springboot project import  dependency jar

    <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-ribbon</artifactId>
    <version>1.4.0.RELEASE</version>
    </dependency>
    best select version is 1.4.0
    let is look resources configuration file application.yml
    #with two client happy
    server:
      port: 9000
    spring:
      application:
        name: ribbon-consumer
    stores:
      ribbon:
        listOfServers: localhost:1001,localhost:1002
        NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule

    the stores is on you dynamic define,and then are fixed。the listOfServers is fixed,the value is the ip and port you repersent。

    the NFLoadBalancerRuleClassName is fixed,and the value is jar inside method you define.

    然后,写一个controller类

    package com.javalol.springcloud.consumer;
    
    import com.javalol.entity.Student;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.cloud.client.ServiceInstance;
    import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    import org.springframework.web.client.RestTemplate;
    
    import java.net.URI;
    import java.util.List;
    
    /**
     * @author liugang
     * @date 2019/6/26 23:54
     **/
    @RestController
    public class Consumer {
    
        @Autowired
        private LoadBalancerClient loadBalancerClient;
    
    //    @Autowired
    //    private RestTemplate restTemplate;
    
        @RequestMapping(value = "consumer")
        public String helloConsumer(){
            ServiceInstance serviceInstance = loadBalancerClient.choose("stores");
            //直接用ribbon场景不存在
            URI uri = URI.create(String.format("http://%s:%s",serviceInstance.getHost(),serviceInstance.getPort()));
            return uri.toString();
    //        return restTemplate.getForEntity("http://MICROSERVICE-STUDENT/student/list",List.class).getBody();
        }
    }

    并且在启动类里面注入一个Bean

    @Bean
        public IRule myRule(){
            return new RandomRule();
        }

    这样,你就会发送返回的uri是随机的。(默认是轮训的)

    现在出现两个问题:

    1,现在设置的ip和端口号是写死的,不能体现出集群的效果?

    2,现在是ribbon是这个一个项目,如果这个项目挂了,就是单点故障了,怎么样去避免,带着单点故障?

  • 相关阅读:
    Lavarel之环境配置 .env
    总结:关于留学网站使用laravel框架的总结
    新版 OSGi 即将发布
    Flex 4 的十大变化
    NetBeans IDE 6.8 Milestone 1 已经可用!
    JSF 2 简介,第 2 部分: 模板及复合组件
    JSF 2 简介,第 2 部分: 模板及复合组件
    Flex 4 的十大变化
    JSF 2 简介,第 1 部分: 流线化 Web 应用程序开发
    JSF 2 简介,第 3 部分: 事件处理、JavaScript 和 Ajax
  • 原文地址:https://www.cnblogs.com/fuckingPangzi/p/11096401.html
Copyright © 2011-2022 走看看