> Java > java지도 시간 > 본문

Spring Cloud로 마이크로서비스의 힘을 활용하세요

DDD
풀어 주다: 2023-09-08 11:24:06
원래의
720명이 탐색했습니다.

마이크로서비스 아키텍처의 등장으로 개발자가 애플리케이션을 구축하고 배포하는 방식이 바뀌었습니다. Spring Cloud는 마이크로서비스 개발 및 관리의 복잡성을 단순화하도록 설계된 Spring 에코시스템의 일부입니다. 이 종합 가이드에서는 Spring Cloud와 그 기능을 살펴보고 간단한 마이크로서비스 애플리케이션을 구축하여 그 기능을 시연해 보겠습니다.

스프링클라우드란?

Spring Cloud는 구성 관리, 서비스 검색, 회로 차단기, 분산 추적 등 분산 시스템의 일반적인 패턴과 문제에 대한 솔루션을 제공하는 도구 및 라이브러리 세트입니다. Spring Boot를 기반으로 구축되었으며 확장 가능하고 내결함성이 있는 마이크로서비스를 쉽게 만들 수 있습니다.

Spring Cloud

  1. 구성 관리: Spring Cloud Config는 분산 애플리케이션에 대한 중앙 집중식 구성 관리를 제공합니다.
  2. 서비스 검색: Spring Cloud Netflix Eureka는 더 나은 로드 밸런싱 및 내결함성을 위해 서비스 등록 및 검색을 지원합니다.
  3. 회로 차단기: Spring Cloud Netflix Hystrix는 서비스 간 액세스 포인트를 격리하여 연속적인 오류를 방지하는 데 도움이 됩니다.
  4. 분산 추적: Spring Cloud Sleuth 및 Zipkin은 더 나은 관찰 가능성과 디버깅을 위해 여러 서비스에 걸쳐 요청 추적을 지원합니다.

Spring Cloud를 사용하여 간단한 마이크로서비스 애플리케이션 구축

이 예에서는 두 가지 서비스가 포함된 간단한 마이크로서비스 애플리케이션을 생성합니다. : Menlo, Monaco, Consolas, "Courier New", 글꼴 크기: 17.1px, 패딩: 2px 4px, 배경색: rgb(249, 242, 244); border-radius: 4px;">user-serviceuser-service和 an order-service주문 서비스 . 또한 중앙 집중식 구성 및 서비스 검색을 위해 Spring Cloud Config 및 Eureka를 사용할 것입니다.

전제 조건

컴퓨터에 다음 소프트웨어가 설치되어 있는지 확인하세요.

  • Java 8 이상
  • Maven 또는 Gradle
  • 원하는 IDE

종속성

<!-- maven -->
<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-config-server</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>
로그인 후 복사


또는

//Gradle 
implementation &#39;org.springframework.cloud:spring-cloud-config-server&#39;
implementation &#39;org.springframework.cloud:spring-cloud-starter-netflix-eureka-client&#39;
implementation &#39;org.springframework.cloud:spring-cloud-starter-netflix-eureka-server&#39;
implementation &#39;org.springframework.cloud:spring-cloud-starter-config&#39;
implementation &#39;org.springframework.cloud:spring-cloud-starter-netflix-eureka-client&#39;
implementation &#39;org.springframework.boot:spring-boot-starter-web&#39;
로그인 후 복사


1단계: Spring Cloud 구성 서버 설정

Spring Initializr(https://start.spring.io/)을 사용하여 새 Spring Boot 프로젝트를 생성하고 구성 서버Config ServerEureka Discovery依赖项。为项目命名config-server

将以下属性添加到您的application.ymland유레카 발견

종속성.

프로젝트 이름 지정

config-server🎜. 🎜🎜🎜🎜다음 속성을 🎜application.yml🎜 파일 내: 🎜🎜🎜 🎜🎜🎜
server:
  port: 8888
spring:
  application:
    name: config-server
  cloud:
    config:
      server:
        git:
          uri: https://github.com/your-username/config-repo.git # Replace with your Git repository URL
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/
로그인 후 복사

通过将以下注释添加到您的主类中来启用 和Config ServerEureka Client

import org.springframework.cloud.config.server.EnableConfigServer;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@EnableConfigServer
@EnableEurekaClient
@SpringBootApplication
public class ConfigServerApplication {
    public static void main(String[] args) {
        SpringApplication.run(ConfigServerApplication.class, args);
    }
로그인 후 복사

第2步:设置Spring Cloud Eureka服务器

使用Spring Initializr创建一个新的 Spring Boot 项目并添加Eureka Server依赖项。为项目命名eureka-server

将以下属性添加到您的application.yml文件中:

server:
  port: 8761
spring:
  application:
    name: eureka-server
eureka:
  client:
    registerWithEureka: false
    fetchRegistry: false
로그인 후 복사

通过将以下注释添加到主类来启用 Eureka Server:

import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@EnableEurekaServer
@SpringBootApplication
public class EurekaServerApplication {
    public static void main(String[] args) {
        SpringApplication.run(EurekaServerApplication.class, args);
    }
}
로그인 후 복사

第三步:创建用户服务

使用 Spring Initializr 创建一个新的 Spring Boot 项目并添加Config ClientEureka DiscoveryWeb依赖项。为项目命名user-service

将以下属性添加到您的bootstrap.yml文件中:

spring:
  application:
    name: user-service
  cloud:
    config:
      uri: http://localhost:8888
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/
로그인 후 복사

创建一个简单REST controllerUser Service

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
    @GetMapping("/users/{id}")
    public String getUser(@PathVariable("id") String id) {
        return "User with ID: " + id;
    }
}
로그인 후 복사

第四步:创建订单服务

使用 Spring Initializr 创建一个新的 Spring Boot 项目并添加Config ClientEureka DiscoveryWeb依赖项。为项目命名order-service

将以下属性添加到您的bootstrap.yml文件中:

spring:
  application:
    name: order-service
  cloud:
    config:
      uri: http://localhost:8888
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/
로그인 후 복사

创建一个简单REST controllerOrder Service

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class OrderController {
    @GetMapping("/orders/{id}")
    public String getOrder(@PathVariable("id") String id) {
        return "Order with ID: " + id;
    }
}
로그인 후 복사

第 5 步:运行应用程序

按以下顺序启动config-servereureka-serveruser-service和应用程序。order-service所有服务运行后,您可以访问 Eureka 仪表板http://localhost:8761并查看已注册的服务。

您现在可以访问用户服务http://localhost:<user-service-port>/users/1和订单服务http://localhost:<order-service-port>/orders/1

结论

在本综合指南中,我们探索了 Spring Cloud 及其功能,并通过构建简单的微服务应用程序展示了其功能。通过利用 Spring Cloud 的强大功能,您可以简化微服务的开发和管理,使它们更具弹性、可扩展性并且更易于维护。使用 Spring Cloud 拥抱微服务世界,将您的应用程序提升到新的高度。

위 내용은 Spring Cloud로 마이크로서비스의 힘을 활용하세요의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!