Rumah> Java> javaTutorial> teks badan

Membina Sistem Perkhidmatan Mikro Pertama Anda dengan Spring Boot: Panduan Pemula

WBOY
Lepaskan: 2024-08-12 22:47:32
asal
675 orang telah melayarinya

Building Your First Microservice System with Spring Boot: A Beginners Guide

pengenalan

Dalam panduan ini, kami akan menelusuri penciptaan sistem perkhidmatan mikro yang ringkas tetapi komprehensif menggunakan Spring Boot. Kami akan merangkumi asas perkhidmatan mikro, menyediakan persekitaran yang diperlukan dan melaksanakan dua perkhidmatan mikro: OrderService dan InventoryService. Selain itu, kami akan menyepadukan penemuan perkhidmatan menggunakan Eureka dan Gateway API untuk mengurus penghalaan antara perkhidmatan.

Apakah perkhidmatan Mikro?

Perkhidmatan mikro ialah gaya seni bina perisian di mana aplikasi dibina sebagai koleksi perkhidmatan kecil dan bebas yang berfungsi bersama. Setiap perkhidmatan adalah serba lengkap dan berkomunikasi dengan orang lain melalui API yang jelas, menjadikan sistem lebih fleksibel, berskala dan lebih mudah untuk diurus.

Seni Bina Sistem

Seni bina sistem kami akan terdiri daripada dua perkhidmatan mikro: OrderService dan InventoryService. OrderService akan menggunakan pangkalan data hubungan (MySQL) untuk menyimpan butiran pesanan, manakala InventoryService akan menggunakan pangkalan data NoSQL (MongoDB) untuk mengurus data inventori. Kami juga akan melaksanakan penemuan perkhidmatan dengan Eureka dan menggunakan Gerbang API untuk permintaan penghalaan.

Persediaan Projek

Sebelum kami mula, pastikan anda telah memasang alatan berikut:

  • IDE: IntelliJ IDEA (diutamakan) atau Eclipse
  • JDK: Versi 17 atau lebih baru
  • Membina Alat: Maven
  • Pangkalan Data: MySQL dan MongoDB

Perkhidmatan mikro 1: Perkhidmatan Pesanan

Langkah 1: Mulakan Projek

  1. Pergi ke Spring Initializr.
  2. Isi butiran projek:
    • Projek: Projek Maven
    • Bahasa: Jawa
    • Spring Boot: 2.5.7 (atau versi yang serasi)
    • Kumpulan: com.sistem pesanan
    • Artifak: perkhidmatan pesanan
    • Nama: perkhidmatan pesanan
    • Nama pakej: com.ordersystem.orderservice
    • Pembungkusan: Balang
    • Jawa: 17
  3. Tambah kebergantungan berikut:
    • Spring Web
    • Data Musim Bunga JPA
    • Pemandu MySQL
    • Lombok
  4. KlikJanauntuk memuat turun projek. Ekstrak fail zip yang dimuat turun dan buka dalam IDE anda.

Langkah 2: Konfigurasi Aplikasi

Buka fail application.properties dalam src/main/resources dan tambahkan konfigurasi berikut:

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
Salin selepas log masuk

Langkah 3: Laksanakan Model

Buat kelas entiti Pesanan dalam src/main/java/com/ordersystem/orderservice/model/Order.java:

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; }
Salin selepas log masuk

Langkah 4: Buat Repositori

Buat antara muka OrderRepository dalam src/main/java/com/ordersystem/orderservice/repository/OrderRepository.java:

package com.ordersystem.orderservice.repository; import com.ordersystem.orderservice.model.Order; import org.springframework.data.jpa.repository.JpaRepository; public interface OrderRepository extends JpaRepository { }
Salin selepas log masuk

Langkah 5: Laksanakan Perkhidmatan

Buat kelas OrderService dalam src/main/java/com/ordersystem/orderservice/service/OrderService.java:

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 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); } }
Salin selepas log masuk

Langkah 6: Buat Pengawal

Buat kelas OrderController dalam src/main/java/com/ordersystem/orderservice/controller/OrderController.java:

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 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); } }
Salin selepas log masuk

Perkhidmatan Mikro 2: Perkhidmatan Inventori

Langkah 1: Mulakan Projek

  1. Pergi ke Spring Initializr.
  2. Isi butiran projek:
    • Projek: Projek Maven
    • Bahasa: Jawa
    • Spring Boot: 2.5.7 (atau versi yang serasi)
    • Kumpulan: com.sistem pesanan
    • Artifak: perkhidmatan inventori
    • Nama: perkhidmatan inventori
    • Nama pakej: com.ordersystem.inventoryservice
    • Pembungkusan: Balang
    • Jawa: 17
  3. Tambah kebergantungan berikut:
    • Spring Web
    • Data Musim Bunga MongoDB
    • Lombok
  4. KlikJanauntuk memuat turun projek. Ekstrak fail zip yang dimuat turun dan buka dalam IDE anda.

Langkah 2: Konfigurasi Aplikasi

Buka fail application.properties dalam src/main/resources dan tambahkan konfigurasi berikut:

spring.data.mongodb.uri=mongodb://localhost:27017/inventoryservice server.port=8082
Salin selepas log masuk

Langkah 3: Laksanakan Model

Buat kelas entiti InventoryItem dalam src/main/java/com/ordersystem/inventoryservice/model/InventoryItem.java:

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; }
Salin selepas log masuk

Langkah 4: Buat Repositori

Buat antara muka InventoryRepository dalam src/main/java/com/ordersystem/inventoryservice/repository/InventoryRepository.java:

package com.ordersystem.inventoryservice.repository; import com.ordersystem.inventoryservice.model.InventoryItem; import org.springframework.data.mongodb.repository.MongoRepository; public interface InventoryRepository extends MongoRepository { }
Salin selepas log masuk

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 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); } }
Salin selepas log masuk

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 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); } }
Salin selepas log masuk

Service Discovery with Eureka

Step 1: Initialize the Eureka Server

  1. Go to Spring Initializr.
  2. 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
  3. Add theEureka Serverdependency.
  4. ClickGenerateto 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
Salin selepas log masuk

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); } }
Salin selepas log masuk

Integrate Services with Eureka

Add the Eureka client dependency to both OrderService and InventoryService:

 org.springframework.cloud spring-cloud-starter-netflix-eureka-client 
Salin selepas log masuk

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
Salin selepas log masuk

Inventory Service:

eureka.client.service-url.defaultZone=http://localhost:8761/eureka/ spring.application.name=inventory-service
Salin selepas log masuk

API Gateway

Step 1: Initialize the API Gateway

  1. Go to Spring Initializr.
  2. 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
  3. Add theGatewayandEureka Discovery Clientdependencies.
  4. ClickGenerateto 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/
Salin selepas log masuk

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); } }
Salin selepas log masuk

Testing the Microservices

  1. Start Eureka Server: Run the Eureka Server application.
  2. Start Order Service: Run the Order Service application.
  3. Start Inventory Service: Run the Inventory Service application.
  4. 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.

Atas ialah kandungan terperinci Membina Sistem Perkhidmatan Mikro Pertama Anda dengan Spring Boot: Panduan Pemula. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

sumber:dev.to
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan
Tentang kita Penafian Sitemap
Laman web PHP Cina:Latihan PHP dalam talian kebajikan awam,Bantu pelajar PHP berkembang dengan cepat!