기술나눔

SpringCloud--유레카 클러스터

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

유레카 등록센터 클러스터

클러스터를 사용하는 이유

등록센터 서버가 하나만 있는 경우 단일 장애 지점이 발생하고 높은 동시성으로 처리할 수 없으므로 클러스터가 필요합니다.

클러스터링 방법

서로 등록할 세 개의 EurekaServer를 준비합니다. 즉, 각 EurekaServer는 자신을 포함하여 모든 EureakServer에 등록해야 합니다. 각 EurekaServer는 서버와 클라이언트 역할을 모두 수행합니다. 다른 마이크로서비스(주문, 사용자)는 등록 주소를 모든 EurekaServer에 지정하기만 하면 됩니다.

암호:

여기서 사용되는 것은 클러스터링 효과를 달성하기 위해 여러 yml 파일을 구성하는 Eureka 모듈입니다.

스타트업 수업

  1. package org.example;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
  5. /**
  6. * @ClassName EurekaStart
  7. * @Author 23
  8. * @Date 2024/7/10 19:12
  9. * @Version 1.0
  10. * @Description TODO
  11. **/
  12. @SpringBootApplication
  13. @EnableEurekaServer
  14. public class EurekaStart {
  15. public static void main(String[] args) {
  16. SpringApplication.run(EurekaStart.class,args);
  17. }
  18. }

yml

  1. spring:
  2. profiles:
  3. active: peer3
  4. ---
  5. spring:
  6. profiles: peer1
  7. application:
  8. name: Eureka1
  9. eureka:
  10. instance:
  11. hostname: localhost
  12. client:
  13. serviceUrl:
  14. defaultZone: http://localhost:10070/eureka/
  15. server:
  16. port: 10070
  17. ---
  18. spring:
  19. profiles: peer2
  20. application:
  21. name: Eureka2
  22. eureka:
  23. instance:
  24. hostname: localhost
  25. client:
  26. serviceUrl:
  27. defaultZone: http://localhost:10071/eureka/
  28. server:
  29. port: 10071
  30. ---
  31. spring:
  32. profiles: peer3
  33. application:
  34. name: Eureka3
  35. eureka:
  36. instance:
  37. hostname: localhost
  38. client:
  39. serviceUrl:
  40. defaultZone: http://localhost:10072/eureka/
  41. server:
  42. port: 10072

pom.xml

  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  3. <modelVersion>4.0.0</modelVersion>
  4. <parent>
  5. <groupId>org.example</groupId>
  6. <artifactId>Springcloud-Netflix</artifactId>
  7. <version>1.0-SNAPSHOT</version>
  8. </parent>
  9. <artifactId>Eureka-Service</artifactId>
  10. <packaging>jar</packaging>
  11. <name>Eureka-Service</name>
  12. <url>http://maven.apache.org</url>
  13. <properties>
  14. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  15. </properties>
  16. <dependencies>
  17. <dependency>
  18. <groupId>junit</groupId>
  19. <artifactId>junit</artifactId>
  20. <version>3.8.1</version>
  21. <scope>test</scope>
  22. </dependency>
  23. <dependency>
  24. <groupId>org.springframework.boot</groupId>
  25. <artifactId>spring-boot-starter-web</artifactId>
  26. </dependency>
  27. <dependency>
  28. <groupId>org.springframework.boot</groupId>
  29. <artifactId>spring-boot-starter-test</artifactId>
  30. </dependency>
  31. <!-- Eureka服务端支持 -->
  32. <dependency>
  33. <groupId>org.springframework.cloud</groupId>
  34. <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
  35. </dependency>
  36. </dependencies>
  37. </project>

서비스 로드 밸런싱

로드 밸런싱이 필요한 이유

동시성을 제공하기 위해 때로는 동일한 서비스 공급자가 여러 개(상품 서비스)를 배포할 수 있습니다. 이 클라이언트는 호출 시 특정 책임 있는 밸런싱 전략에 따라 로드 호출을 완료해야 합니다.

서비스 제공업체 구성

  1. spring:
  2. profiles:
  3. active: order2
  4. ---
  5. server:
  6. port: 10010
  7. spring:
  8. profiles: order1
  9. application:
  10. name: order-service
  11. eureka:
  12. client:
  13. service-url:
  14. defaultZone: http://localhost:10072/eureka
  15. instance:
  16. prefer-ip-address: true
  17. ---
  18. server:
  19. port: 10012
  20. spring:
  21. profiles: order2
  22. application:
  23. name: order-service
  24. eureka:
  25. client:
  26. service-url:
  27. defaultZone: http://localhost:10072/eureka
  28. instance:
  29. prefer-ip-address: true

일반적인 로드 밸런싱 구현 기술

리본

RestTmplate을 통해 URL로 서비스 호출을 완료합니다.

코드 구현(서비스 소비자 측):

  1. package org.example.Controller;
  2. import org.example.domain.Order;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.cloud.client.ServiceInstance;
  5. import org.springframework.cloud.client.discovery.DiscoveryClient;
  6. import org.springframework.web.bind.annotation.GetMapping;
  7. import org.springframework.web.bind.annotation.PathVariable;
  8. import org.springframework.web.bind.annotation.RequestMapping;
  9. import org.springframework.web.bind.annotation.RestController;
  10. import org.springframework.web.client.RestTemplate;
  11. import java.util.Arrays;
  12. import java.util.List;
  13. /**
  14. * @ClassName UserController
  15. * @Author 23
  16. * @Date 2024/7/10 18:52
  17. * @Version 1.0
  18. * @Description TODO
  19. **/
  20. @RestController
  21. @RequestMapping("/User")
  22. public class UserControllerrlb {
  23. @Autowired
  24. private RestTemplate restTemplate;
  25. // @Autowired
  26. // private DiscoveryClient discoveryClient;
  27. @GetMapping("/getOrder/{id}")
  28. public List<Order> getOrderById(@PathVariable("id") Integer id) {
  29. // Order[] order = restTemplate.getForObject("http://localhost:10010/OrderService/user/" + id, Order[].class);
  30. // return Arrays.asList(order);
  31. // List<ServiceInstance> instances=discoveryClient.getInstances("order-service");//通过服务的名字去获取服务实例
  32. // ServiceInstance serviceInstance=instances.get(0);//定死只获取第一个服务实例对象
  33. // String ip=serviceInstance.getHost();//获取服务对象ip
  34. // int port=serviceInstance.getPort();//获取获取的实例对象的服务端口号
  35. Order[] orders=restTemplate.getForObject("http://Order-Service/OrderService/user/"+id,Order[].class);
  36. return Arrays.asList(orders);
  37. }
  38. }

리본 로드 밸런싱 호출

리본(Ribbon)은 넷플릭스가 출시한 클라우드 미들 레이어 서비스의 오픈소스 프로젝트로 클라이언트 로드 밸런싱 알고리즘을 제공하는 것이 주요 기능이다. 리본 클라이언트 구성 요소는 연결 시간 초과, 재시도 등과 같은 일련의 전체 구성 항목을 제공합니다. 간단히 말해서 리본은 클라이언트 로드 밸런서입니다. 구성 파일에 로드 밸런서 뒤에 있는 모든 시스템을 나열할 수 있으며 리본은 특정 규칙(예: 단순 폴링, 무작위 연결 등)에 따라 자동으로 연결하도록 도와줍니다. 기계에서는 리본을 사용하여 사용자 정의 로드 밸런싱 알고리즘을 쉽게 구현할 수 있습니다. 리본은 특정 규칙에 따라 서비스의 여러 서비스 인스턴스에 대한 로드 밸런싱 호출을 완료할 수 있는 클라이언트 로드 밸런서입니다.

개략도:

OpenFeign 로드 밸런싱

OpenFeign은 웹 서비스 호출을 더 쉽게 만드는 것이 목적인 선언적 웹 서비스 클라이언트입니다. Feign은 HTTP 요청에 대한 인터페이스 템플릿을 제공합니다(액세스 주소가 표시되어 있음). 간단한 인터페이스를 작성하고 주석을 삽입하여 HTTP 요청의 매개변수, 형식, 주소 및 기타 정보를 정의할 수 있습니다. OpenFeign은 HTTP 요청을 완전히 프록시(동적 프록시)합니다. 서비스 요청 및 관련 처리를 완료하기 위한 메서드처럼 호출하기만 하면 됩니다. Feign은 Ribbon과 Hystrix(Hystrix에 대해서는 나중에 설명하겠습니다)를 통합하므로 더 이상 이 두 구성 요소를 명시적으로 사용할 필요가 없습니다.

부하 분산 전략

이룰

다양한 IRule 하위 클래스를 구성하면 다양한 로드 밸런싱 전략을 선택할 수 있습니다. 즉, 특정 전략이 포함된 서비스 목록에서 서비스를 선택하여 호출을 완료할 수 있습니다. 물론 맞춤설정도 가능합니다. 따라서 로드 밸런싱 전략은 기본 제공 전략과 사용자 정의 전략으로 나눌 수 있습니다.

내장된 로드 밸런싱 전략