• springcloud(五):Ribbon负载均衡机制


    1. 测试自定义负载均衡规则

    1.1 服务器

    创建first-boot项目:

    pom:

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <groupId>org.crazyi.cloud</groupId>
        <artifactId>first-boot</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
                <version>1.5.7.RELEASE</version>
            </dependency>
        </dependencies>
        
    </project>

    Person:

    package org.crazyit.cloud;
    
    public class Person {
    
        private Integer id;
        private String name;
        private Integer age;
        private String message;
        public Integer getId() {
            return id;
        }
        public void setId(Integer id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public Integer getAge() {
            return age;
        }
        public void setAge(Integer age) {
            this.age = age;
        }
        public String getMessage() {
            return message;
        }
        public void setMessage(String message) {
            this.message = message;
        }
        
    }

    MyController:

    package org.crazyit.cloud;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    @Controller
    public class MyController {
    
        @GetMapping("/hello")
        @ResponseBody
        public String hello() {
            return "Hello World";
        }
    }

    MyRestController:

    package org.crazyit.cloud;
    
    import javax.servlet.http.HttpServletRequest;
    
    import org.springframework.http.MediaType;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    public class MyRestController {
    
        @RequestMapping(value = "/person/{id}", method = RequestMethod.GET, 
                produces = MediaType.APPLICATION_JSON_VALUE)
        public Person getPerson(@PathVariable Integer id, HttpServletRequest request) {
            Person p = new Person();
            p.setId(id);
            p.setName("angus");
            p.setAge(30);
            p.setMessage(request.getRequestURL().toString());
            return p;
        }
    }

    FirstApp:

    package org.crazyit.cloud;
    
    import java.util.Scanner;
    
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.boot.builder.SpringApplicationBuilder;
    
    @SpringBootApplication
    public class FirstApp {
    
        public static void main(String[] args) {
            Scanner scan = new Scanner(System.in);
            String port = scan.nextLine();
            new SpringApplicationBuilder(FirstApp.class).properties("server.port=" + port).run(args);
            
        }
    
    }

    1.2 客户端

    创建项目user-ribbon:

    直接使用:

    LBMain:

    package org.crazyit.cloud;
    
    import java.util.ArrayList;
    import java.util.List;
    
    import com.netflix.loadbalancer.BaseLoadBalancer;
    import com.netflix.loadbalancer.ILoadBalancer;
    import com.netflix.loadbalancer.Server;
    
    public class LBMain {
    
        public static void main(String[] args) {
            ILoadBalancer lb = new BaseLoadBalancer();
            List<Server> servers = new ArrayList<Server>();
            servers.add(new Server("localhost", 8080));
            servers.add(new Server("localhost", 8081));
            
            lb.addServers(servers);
            for(int i = 0; i < 10; i++) {
                Server s = lb.chooseServer(null);
                System.out.println(s);
            }
        }
    
    }

    使用Rule:

    MyRule:

    package org.crazyit.cloud;
    
    import java.util.List;
    import java.util.Random;
    
    import com.netflix.loadbalancer.ILoadBalancer;
    import com.netflix.loadbalancer.IRule;
    import com.netflix.loadbalancer.Server;
    
    public class MyRule implements IRule {
        
        private ILoadBalancer lb;
    
        public Server choose(Object key) {
            Random r = new Random();
            int rNum = r.nextInt(10);
            
            List<Server> servers = lb.getAllServers();
            
            if(rNum > 7) {
                return getServerByPort(servers, 8081);
            }
            return getServerByPort(servers, 8080);
        }
        
        private Server getServerByPort(List<Server> servers, int port) {
            for(Server s : servers) {
                if(s.getPort() == port) {
                    return s;
                }
            }
            return null;
        }
    
        public void setLoadBalancer(ILoadBalancer lb) {
            this.lb = lb;
        }
    
        public ILoadBalancer getLoadBalancer() {
            return this.lb;
        }
    
    }

    TestMyRule:

    package org.crazyit.cloud;
    
    import java.util.ArrayList;
    import java.util.List;
    
    import com.netflix.loadbalancer.BaseLoadBalancer;
    import com.netflix.loadbalancer.ILoadBalancer;
    import com.netflix.loadbalancer.Server;
    
    public class TestMyRule {
    
        public static void main(String[] args) {
            BaseLoadBalancer lb = new BaseLoadBalancer();
            MyRule rule = new MyRule();
            rule.setLoadBalancer(lb);
            lb.setRule(rule);
            
            List<Server> servers = new ArrayList<Server>();
            servers.add(new Server("localhost", 8080));
            servers.add(new Server("localhost", 8081));
            lb.addServers(servers);
            for(int i = 0; i < 10; i++) {
                Server s = lb.chooseServer(null);
                System.out.println(s);
            }
        }
    
    }

    TestRibbon:

    package org.crazyit.cloud;
    
    import com.netflix.client.ClientFactory;
    import com.netflix.client.http.HttpRequest;
    import com.netflix.client.http.HttpResponse;
    import com.netflix.config.ConfigurationManager;
    import com.netflix.niws.client.http.RestClient;
    
    public class TestRibbon {
    
        public static void main(String[] args) throws Exception {
            ConfigurationManager.getConfigInstance().setProperty(
                      "my-client.ribbon.listOfServers", "localhost:8080,localhost:8081");
            ConfigurationManager.getConfigInstance().setProperty(
                      "my-client.ribbon.NFLoadBalancerRuleClassName", MyRule.class.getName());
            
            // 获取REST请求客户端
            RestClient client = (RestClient) ClientFactory
                    .getNamedClient("my-client");
            // 创建请求实例
            HttpRequest request = HttpRequest.newBuilder().uri("/person/1").build();
            // 发 送10次请求到服务器中
            for (int i = 0; i < 10; i++) {
                HttpResponse response = client.executeWithLoadBalancer(request);
                String result = response.getEntity(String.class);
                System.out.println(result);
            }
        }
    
    }
  • 相关阅读:
    jsonp的实现原理和缺点
    vue $set的使用初了解
    js将多维数组转换为一维数组
    微信小程序之页面打开数量限制
    ZOJ 1463 Brackets Sequence
    CSUOJ 1248 非变性聚丙烯酰胺凝胶电泳
    ZOJ 1524 Supermarket
    POJ 1012 Joseph
    ZOJ 1276 Optimal Array Multiplication Sequence
    POJ 1742 Coins
  • 原文地址:https://www.cnblogs.com/liuhui0308/p/13908218.html
Copyright © 2020-2023  润新知