Spring Boot를 사용하여 첫 번째 마이크로서비스 시스템 구축: 초보자 가이드
소개
이 가이드에서는 Spring Boot를 사용하여 간단하면서도 포괄적인 마이크로서비스 시스템을 만드는 과정을 살펴보겠습니다. 마이크로서비스의 기본 사항, 필요한 환경 설정, 두 가지 마이크로서비스인 OrderService 및 InventoryService 구현을 다룹니다. 또한 Eureka와 API 게이트웨이를 사용하여 서비스 검색을 통합하여 서비스 간 라우팅을 관리할 예정입니다.
마이크로서비스란 무엇입니까?
마이크로서비스는 함께 작동하는 소규모의 독립적인 서비스 모음으로 애플리케이션을 구축하는 소프트웨어 아키텍처 스타일입니다. 각 서비스는 독립적이며 잘 정의된 API를 통해 다른 서비스와 통신하므로 시스템을 더욱 유연하고 확장 가능하며 관리하기 쉽게 만듭니다.
시스템 아키텍처
우리 시스템의 아키텍처는 OrderService와 InventoryService라는 두 가지 마이크로서비스로 구성됩니다. OrderService는 관계형 데이터베이스(MySQL)를 사용하여 주문 세부 정보를 저장하고 InventoryService는 NoSQL 데이터베이스(MongoDB)를 사용하여 재고 데이터를 관리합니다. 또한 Eureka로 서비스 검색을 구현하고 요청 라우팅을 위해 API 게이트웨이를 사용할 것입니다.
프로젝트 설정
시작하기 전에 다음 도구가 설치되어 있는지 확인하세요.
- IDE: IntelliJ IDEA(선호) 또는 Eclipse
- JDK: 버전 17 이상
- 빌드 도구: Maven
- 데이터베이스: MySQL 및 MongoDB
마이크로서비스 1: 주문 서비스
1단계: 프로젝트 초기화
- Spring 초기화로 이동하세요.
- 프로젝트 세부정보를 입력하세요.
- 프로젝트: 메이븐 프로젝트
- 언어: 자바
- Spring Boot: 2.5.7(또는 호환 버전)
- 그룹: com.ordersystem
- 아티팩트: 주문-서비스
- 이름: 주문 서비스
- 패키지 이름: com.ordersystem.orderservice
- 포장: 항아리
- 자바: 17
- 다음 종속성을 추가합니다.
- 스프링웹
- 스프링 데이터 JPA
- MySQL 드라이버
- 롬복
- 생성을 클릭하여 프로젝트를 다운로드하세요. 다운로드한 zip 파일의 압축을 풀고 IDE에서 엽니다.
2단계: 애플리케이션 구성
src/main/resources에서 application.properties 파일을 열고 다음 구성을 추가합니다.
spring.datasource.url=jdbc:mysql://localhost:3306/orderservice spring.datasource.username=root spring.datasource.password=yourpassword spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.jpa.hibernate.ddl-auto=update spring.jpa.show-sql=true spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect server.port=8081
3단계: 모델 구현
src/main/java/com/ordersystem/orderservice/model/Order.java에 Order 엔터티 클래스를 생성합니다.
package com.ordersystem.orderservice.model; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.*; @Data @AllArgsConstructor @NoArgsConstructor @Entity @Table(name = "orders") public class Order { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String product; private int quantity; private double price; }
4단계: 리포지토리 생성
src/main/java/com/ordersystem/orderservice/repository/OrderRepository.java에 OrderRepository 인터페이스를 생성합니다.
package com.ordersystem.orderservice.repository; import com.ordersystem.orderservice.model.Order; import org.springframework.data.jpa.repository.JpaRepository; public interface OrderRepository extends JpaRepository<Order, Long> { }
5단계: 서비스 구현
src/main/java/com/ordersystem/orderservice/service/OrderService.java에 OrderService 클래스를 생성합니다.
package com.ordersystem.orderservice.service; import com.ordersystem.orderservice.model.Order; import com.ordersystem.orderservice.repository.OrderRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class OrderService { @Autowired private OrderRepository orderRepository; public List<Order> getAllOrders() { return orderRepository.findAll(); } public Order getOrderById(Long id) { return orderRepository.findById(id).orElse(null); } public Order createOrder(Order order) { return orderRepository.save(order); } public void deleteOrder(Long id) { orderRepository.deleteById(id); } }
6단계: 컨트롤러 생성
src/main/java/com/ordersystem/orderservice/controller/OrderController.java에 OrderController 클래스를 생성합니다.
package com.ordersystem.orderservice.controller; import com.ordersystem.orderservice.model.Order; import com.ordersystem.orderservice.service.OrderService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping("/api/orders") public class OrderController { @Autowired private OrderService orderService; @GetMapping public List<Order> getAllOrders() { return orderService.getAllOrders(); } @GetMapping("/{id}") public Order getOrderById(@PathVariable Long id) { return orderService.getOrderById(id); } @PostMapping public Order createOrder(@RequestBody Order order) { return orderService.createOrder(order); } @DeleteMapping("/{id}") public void deleteOrder(@PathVariable Long id) { orderService.deleteOrder(id); } }
마이크로서비스 2: 인벤토리 서비스
1단계: 프로젝트 초기화
- Spring 초기화로 이동하세요.
- 프로젝트 세부정보를 입력하세요.
- 프로젝트: 메이븐 프로젝트
- 언어: 자바
- Spring Boot: 2.5.7(또는 호환 버전)
- 그룹: com.ordersystem
- 아티팩트: 재고 서비스
- 이름: Inventory-service
- 패키지 이름: com.ordersystem.inventoryservice
- 포장: 항아리
- 자바: 17
- 다음 종속성을 추가합니다.
- 스프링웹
- 스프링 데이터 MongoDB
- 롬복
- 생성을 클릭하여 프로젝트를 다운로드하세요. 다운로드한 zip 파일의 압축을 풀고 IDE에서 엽니다.
2단계: 애플리케이션 구성
src/main/resources에서 application.properties 파일을 열고 다음 구성을 추가합니다.
spring.data.mongodb.uri=mongodb://localhost:27017/inventoryservice server.port=8082
3단계: 모델 구현
src/main/java/com/ordersystem/inventoryservice/model/InventoryItem.java에 InventoryItem 엔터티 클래스를 생성합니다.
package com.ordersystem.inventoryservice.model; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; @Data @AllArgsConstructor @NoArgsConstructor @Document(collection = "inventory") public class InventoryItem { @Id private String id; private String product; private int quantity; }
4단계: 리포지토리 생성
src/main/java/com/ordersystem/inventoryservice/repository/InventoryRepository.java에 InventoryRepository 인터페이스를 생성합니다.
package com.ordersystem.inventoryservice.repository; import com.ordersystem.inventoryservice.model.InventoryItem; import org.springframework.data.mongodb.repository.MongoRepository; public interface InventoryRepository extends MongoRepository<InventoryItem, String> { }
Step 5: Implement the Service
Create the InventoryService class in src/main/java/com/ordersystem/inventoryservice/service/InventoryService.java:
package com.ordersystem.inventoryservice.service; import com.ordersystem.inventoryservice.model.InventoryItem; import com.ordersystem.inventoryservice.repository.InventoryRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class InventoryService { @Autowired private InventoryRepository inventoryRepository; public List<InventoryItem> getAllItems() { return inventoryRepository.findAll(); } public InventoryItem getItemById(String id) { return inventoryRepository.findById(id).orElse(null); } public InventoryItem createItem(InventoryItem item) { return inventoryRepository.save(item); } public void deleteItem(String id) { inventoryRepository.deleteById(id); } }
Step 6: Create the Controller
Create the InventoryController class in src/main/java/com/ordersystem/inventoryservice/controller/InventoryController.java:
package com.ordersystem.inventoryservice.controller; import com.ordersystem.inventoryservice.model.InventoryItem; import com.ordersystem.inventoryservice.service.InventoryService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping("/api/inventory") public class InventoryController { @Autowired private InventoryService inventoryService; @GetMapping public List<InventoryItem> getAllItems() { return inventoryService.getAllItems(); } @GetMapping("/{id}") public InventoryItem getItemById(@PathVariable String id) { return inventoryService.getItemById(id); } @PostMapping public InventoryItem createItem(@RequestBody InventoryItem item) { return inventoryService.createItem(item); } @DeleteMapping("/{id}") public void deleteItem(@PathVariable String id) { inventoryService.delete Item(id); } }
Service Discovery with Eureka
Step 1: Initialize the Eureka Server
- Go to Spring Initializr.
- Fill in the project details:
- Project: Maven Project
- Language: Java
- Spring Boot: 2.5.7 (or a compatible version)
- Group: com.ordersystem
- Artifact: eureka-server
- Name: eureka-server
- Package name: com.ordersystem.eurekaserver
- Packaging: Jar
- Java: 17
- Add the Eureka Server dependency.
- Click Generate to download the project. Extract the downloaded zip file and open it in your IDE.
Step 2: Configure the Eureka Server
Open the application.properties file in src/main/resources and add the following configuration:
server.port=8761 eureka.client.register-with-eureka=false eureka.client.fetch-registry=false
Step 3: Enable Eureka Server
Annotate the main application class in src/main/java/com/ordersystem/eurekaserver/EurekaServerApplication.java with @EnableEurekaServer:
package com.ordersystem.eurekaserver; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; @SpringBootApplication @EnableEurekaServer public class EurekaServerApplication { public static void main(String[] args) { SpringApplication.run(EurekaServerApplication.class, args); } }
Integrate Services with Eureka
Add the Eureka client dependency to both OrderService and InventoryService:
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency>
Add Eureka client configuration to the application.properties files:
Order Service:
eureka.client.service-url.defaultZone=http://localhost:8761/eureka/ spring.application.name=order-service
Inventory Service:
eureka.client.service-url.defaultZone=http://localhost:8761/eureka/ spring.application.name=inventory-service
API Gateway
Step 1: Initialize the API Gateway
- Go to Spring Initializr.
- Fill in the project details:
- Project: Maven Project
- Language: Java
- Spring Boot: 2.5.7 (or a compatible version)
- Group: com.ordersystem
- Artifact: api-gateway
- Name: api-gateway
- Package name: com.ordersystem.apigateway
- Packaging: Jar
- Java: 17
- Add the Gateway and Eureka Discovery Client dependencies.
- Click Generate to download the project. Extract the downloaded zip file and open it in your IDE.
Step 2: Configure the API Gateway
Open the application.yml file in src/main/resources and add the following configuration:
server: port: 8080 spring: application: name: api-gateway cloud: gateway: routes: - id: order-service uri: lb://order-service predicates: - Path=/api/orders/** - id: inventory-service uri: lb://inventory-service predicates: - Path=/api/inventory/** eureka: client: service-url: defaultZone: http://localhost:8761/eureka/
Step 3: Enable Discovery Client
Annotate the main application class in src/main/java/com/ordersystem/apigateway/ApiGatewayApplication.java with @EnableDiscoveryClient:
package com.ordersystem.apigateway; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; @SpringBootApplication @EnableDiscoveryClient public class ApiGatewayApplication { public static void main(String[] args) { SpringApplication.run(ApiGatewayApplication.class, args); } }
Testing the Microservices
- Start Eureka Server: Run the Eureka Server application.
- Start Order Service: Run the Order Service application.
- Start Inventory Service: Run the Inventory Service application.
- Start API Gateway: Run the API Gateway application.
Use Postman or any other API client to test the endpoints through the API Gateway:
- Create Order: POST http://localhost:8080/api/orders
- Get Orders: GET http://localhost:8080/api/orders
- Create Inventory Item: POST http://localhost:8080/api/inventory
- Get Inventory Items: GET http://localhost:8080/api/inventory
Conclusion
In this guide, we've built a simple microservices system using Spring Boot. We created two microservices (OrderService and InventoryService), integrated service discovery with Eureka, and set up an API Gateway for routing requests. This architecture allows for scalable and maintainable microservices that can be easily extended in the future.
위 내용은 Spring Boot를 사용하여 첫 번째 마이크로서비스 시스템 구축: 초보자 가이드의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

일부 애플리케이션이 제대로 작동하지 않는 회사의 보안 소프트웨어에 대한 문제 해결 및 솔루션. 많은 회사들이 내부 네트워크 보안을 보장하기 위해 보안 소프트웨어를 배포 할 것입니다. ...

많은 응용 프로그램 시나리오에서 정렬을 구현하기 위해 이름으로 이름을 변환하는 솔루션, 사용자는 그룹으로, 특히 하나로 분류해야 할 수도 있습니다.

시스템 도킹의 필드 매핑 처리 시스템 도킹을 수행 할 때 어려운 문제가 발생합니다. 시스템의 인터페이스 필드를 효과적으로 매핑하는 방법 ...

IntellijideAultimate 버전을 사용하여 봄을 시작하십시오 ...

데이터베이스 작업에 MyBatis-Plus 또는 기타 ORM 프레임 워크를 사용하는 경우 엔티티 클래스의 속성 이름을 기반으로 쿼리 조건을 구성해야합니다. 매번 수동으로 ...

Java 객체 및 배열의 변환 : 캐스트 유형 변환의 위험과 올바른 방법에 대한 심층적 인 논의 많은 Java 초보자가 객체를 배열로 변환 할 것입니다 ...

전자 상거래 플랫폼에서 SKU 및 SPU 테이블의 디자인에 대한 자세한 설명이 기사는 전자 상거래 플랫폼에서 SKU 및 SPU의 데이터베이스 설계 문제, 특히 사용자 정의 판매를 처리하는 방법에 대해 논의 할 것입니다 ...

Redis 캐싱 솔루션은 제품 순위 목록의 요구 사항을 어떻게 인식합니까? 개발 과정에서 우리는 종종 a ... 표시와 같은 순위의 요구 사항을 처리해야합니다.
