서문 : 마이크로 서비스 아키텍처는 필연적으로 단일 마이크로 서비스의 여러 인스턴스를 가지고 있습니다. 그렇다면 클라이언트는 어떻게 여러 마이크로 서비스 인스턴스에 요청을 할당 할 수 있습니까? 여기서 우리는로드 밸런싱을 사용해야합니다
1. 리본 소개
리본은 Netflix가 출시 한로드 밸런서로 HTTP 및 TCP 클라이언트의 동작을 제어하는 데 도움이됩니다. 리본의 서비스 제공 업체 주소 목록을 구성한 후 리본은 일부로드 밸런싱 알고리즘을 기반으로 서비스 소비자가 요청하는 데 자동으로 도움이 될 수 있습니다. 리본은 폴링, 무작위성 등과 같은 기본적으로 많은로드 밸런싱 알고리즘을 제공합니다. 이는 또한 사용자 정의 할 수 있습니다.
리본의 github : https://github.com/netflix/ribbon
Springcloud에서 리본과 유레카를 사용할 때 리본은 EureKaserver에서 서비스 제공 업체 주소 목록을 자동으로 얻고로드 밸런싱 알고리즘을 기반으로합니다.
2. 리본 실제 전투
1. eurekaserver, eurekaclient1, eurekaclient2를 만듭니다. 이전에 Eureka의 사용에 대해 언급 했으므로 여기에 코드가 있습니다.
eurekaserver :
ServerApplication.java
@SpringBootApplication@enableEureKaserPublic Class ServerApplication {public static void main (String [] args) {springApplication.run (serverApplication.class, args); }}pom.xml
<? xml version = "1.0"encoding = "utf-8"?> <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.xsd"> <modeversion> 4.0.0 </modelversion> <groupid> com.cn </groupid> <artifactid> eureeko-ritifbon-serer artifbon-sereReReReReReReReReReReReReReReTer </groupId <버전> 1.0-snapshot </version> <properties> <project.build.sourceencoding> utf-8 </project.build.build.sourceencoding> <java.version> 1.8 </java.version> </properties> <부모> <groupid> org.springframework.boot> <Artifactid> Spring-Boot-Starter-Parent </artifactid> <bersion> 1.5.13. Release </version> </parent> <pectionency> <groupid> org.springframework. </groupId> <artifactid> </artifactid> </dependency> </groupid> org.spramwork.springwork. <Artifactid> Spring-Cloud-Starter-Eureka-Server </artifactid> </fectionency> </dependency> </dependency> </fectionency> <pectionencymanagement> <pectionements> <groupId> org.springframework.cloud </groupid> <artifactid> spring-cloud-dependencies </artifactid> </artifactid> <type> pom </type> <cope> 가져 오기 </scope> </scope> </fectionency> </fectionency> </fectionencymanagement> <!-스프링 부트 Maven 플러그인 추가-> <build> <flugin> <flugin> <groupid> org.springframework.boot </groupid> arglifact-maven-spramin </artifactid> </flugin> </빌드> </project>
application.properties
Server.port = 8761#참고 :이 두 구성은 기본적으로 사실입니다. 거짓으로 변경해야합니다. 그렇지 않으면 오류 가보고됩니다. Connot Connect Server# EureKaserver Eureka.client에 등록할지 여부를 나타냅니다. Register-with-eureka = false# eureKaserver eureka.client.fetch-registry.client.service-url.defaultzone = http : // localhost : 8761/eeuka//eeuka//eeuka//eureka/eeuka/eureka에서 등록 정보를 얻을 것인지를 나타냅니다.
eurekaclient1 :
pom.xml
<? xml version = "1.0"encoding = "utf-8"?> <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"> <modeversion> 4.0.0 </modelversion> <groupid> com.cn </groupid> <artifactid> eureca-critient <버전> 1.0-snapshot </version> <properties> <project.build.sourceencoding> utf-8 </project.build.build.sourceencoding> <java.version> 1.8 </java.version> </properties> <부모> <groupid> org.springframework.boot> <Artifactid> Spring-Boot-starter-Parent </artifactid> <bersion> 1.5.13. Release </version> </parent> <pectional> <pectiency> <groupid> org.springframework.cloud </groupid> <artifactid> spring-cloud-starter-ribbon </artifactid> </delation> <groupid> org.springframework.cloud </groupid> <artifactid> spring-cloud-starter-eureka </artifactid> </eppendency> </dependency> </dependency> <pelection> <groupid> org.spramework.cloud </groupid> <artifactid> spring-cloud decnecties </artifactid> <버전> edgware.sr3 </version> <type> pom </type> <scope> 가져 오기 </scope> </spectency> </fectionency> </fectionencymanagement> <!-스프링 부트 Maven 플러그인 추가-> <플러그인> <grupin> <groupid> org.springframewort </groupid> <Artifactid> Spring-Boot-Maven-Plugin </artifactid> </plugin> </plugins> </build> </project>
Server.port = 8762spring.application.name = client-8762eureka.client.service-url.defaultzone = http : // localhost : 8761/eureka/
스타트 업 클래스의 컨테이너에 resttemplate 원격 통화 인스턴스를 추가하고로드 밸런스 주석을 추가하여 resttemplate를로드 밸런싱을 할 수 있도록합니다.
@springbootApplication@enablediscoveryClientPublic Class ClientApplication {public static void main (String [] args) {springApplication.run (clientApplication.class, args); }/** * @description : resttemplate에로드 밸런싱 기능을 추가하기 위해 @loadbalanced 주석을 추가하면 * @param : * @author : * @date : 2018/6/15 */@bean @loadbalanced public resttemplate getRestTemplate () {return new RestTemplate (); }}컨트롤러, RestTemplate 및 LoadBalancerClient 인스턴스를 생성하십시오.
package com.cn.controller; import org.springframework.beans.bean.bean.bean.bean.bean.aUtowired; import org.springframework.cloud.client.serviceInstance; import org.springframework.cloud.cloud.loadbalancer.loadbalancerclient; import org.springframework.sterepotyp.controller; org.springframework.web.bind.annotation.getmapping; import org.springframework.bind.annotation.responsebody; import org.springframework.web.client.resttemplate;/** * @program : springcloud-example * @description : * @create : 2018-05-15-55- **/ @ControllerPublic 클래스 RibbonController {@autowired private loadbalancerclient loadbalancerclient; @autowired 개인 resttemplate resttemplate; @GetMapping ( "/loadInstance") @ResponseBody Public String LoadInstance () {ServiceInstance 선택 = this.loadBalancerClient.choose ( "Client-87"); System.out.println (선택 .getServiceId ()+":"+선택 .gethost ()+":"+선택 .getport ()); return chelect.getServiceId () + ":" + 선택 .gethost () + ":" + 선택 .getport (); }} 패키지 com.cn; import org.springframework.boot.springApplication; import org.springframework.boot.autoconfigure.springbootApplication; import org.springframework.cloud.cloud.client.discovery.enablediscoveryclient;/** @@program : spring-explack : * @deplask : 535504 *@Create : 2018-06-15 16:05 **/@springbootApplication@enableableDiscoveryClientPublic ClientApplication {public static void main (String [] args) {springApplication.run (clientApplication.class, args); }}eurekaclient2 :
pom.xml은 eurekaclient1과 일치합니다
application.xml :
Server.port = 8763spring.application.name = client-87eureka.client.service-url.defaultzone = http : // localhost : 8761/eureka
ClientController.java :
package com.cn.contorller; import org.springframework.steretype.controller; import org.springframework.bind.bind.bind.bind.getmapping; import org.springframework.bind.annotation.response.response.respronge.respronge.bind.bind.bind.bind.bind.bind.bind.annotation.respronge : * @@create : * @Decrate : 2018-06-15 16:12 **/ @controllerpublic class clientController {@getMapping ( "/getUser") @ResponseBody public String getUser () {System.out.println ( "사용자 성공"); "사용자가 성공하기"를 반환합니다. }}2. 시작 시퀀스 :
①. 시작 eurekaserver =》 eurekaclient1 =》 eurekaclient2;
②. 그런 다음 eureKaclient2에서 server.port = 8764의 application.properties의 server.port = 8763을 변경하고 프로젝트를 다시 시작하십시오.
③. 다음과 같이 EureKaserver 구성 페이지 (http : // localhost : 8761/)를 엽니 다.
④. 우리는 주소 표시 줄에 http : // localhost : 8762/loadinstance를 입력하고 몇 번 새로 고치고 있습니다. 아래 그림과 같이 포트 인스턴스는 우리가 호출 할 때마다 다를 수 있습니다.
⑤. 그림과 같이 콘솔을보고 있습니다.
이 시점에서 리본은 이미 시작되었습니다. 매우 간단하지 않습니까? 그러나 이것은 가장 간단한 응용 프로그램이며 시간 낭비입니다 ... 학습의 끝이 없습니다!
샘플 코드 : https://gitee.com/lfalex/springcloud-example