本文共 4722 字,大约阅读时间需要 15 分钟。
学习微服务架构,不仅要理解其基本概念和核心组件,还需要通过实践来掌握。本文以电商中的常见业务场景——创建订单为例,结合Spring Cloud Finchley.SR1体系,讲解如何构建微服务架构。
在开始构建微服务之前,需要具备以下基础知识:
本文将使用以下Spring Cloud组件:
为了更好地展示微服务的优势,本文简化了现实中下单过程的复杂性,仅保留两个主要操作:
基于上述业务场景,设计了以下微服务架构:
基于上述架构,创建了一个Maven项目,包含五个子模块:
4.0.0 org.springframework.boot spring-boot-starter-parent 2.0.1.RELEASE com.no.one microservice-base pom 1.0-SNAPSHOT 1.8 org.springframework.cloud spring-cloud-dependencies Finchley.SR1 pom import discovery-server api-gateway-server order-service product-service user-service org.springframework.boot spring-boot-maven-plugin
创建Eureka注册中心,首先在discovery-server模块的POM中引入依赖:
org.springframework.cloud spring-cloud-starter-netflix-eureka-server
创建主类DiscoveryApplication:
@SpringBootApplication@EnableEurekaServerpublic class DiscoveryApplication { public static void main(String[] args) { SpringApplication.run(DiscoveryApplication.class, args); }} 配置文件bootstrap.properties:
spring.application.name=discovery-server
配置文件application.properties:
server.port=8761eureka.instance.hostname=localhosteureka.client.registerWithEureka=falseeureka.client.fetchRegistry=falseeureka.client.serviceUrl.defaultZone=http://${eureka.instance.hostname}:${server.port}/eureka/ 在api-gateway-server模块的POM中引入依赖:
org.springframework.cloud spring-cloud-starter-netflix-eureka-client org.springframework.cloud spring-cloud-starter-netflix-zuul
创建主类GatewayApplication:
@SpringBootApplication@EnableDiscoveryClient@EnableZuulProxypublic class GatewayApplication { public static void main(String[] args) { SpringApplication.run(GatewayApplication.class, args); }} 配置文件bootstrap.properties:
spring.application.name=api-gateway-server
配置文件application.properties:
server.port=9002eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/zuul.prefix=/apizuul.routes.user-service.path=/user-service/**zuul.routes.user-service.serviceId=user-servicezuul.routes.product-service.path=/product-service/**zuul.routes.product-service.serviceId=product-servicezuul.routes.order-service.path=/order-service/**zuul.routes.order-service.serviceId=order-service
以OrderService为例,构建具体业务服务。创建order-service模块的POM:
org.springframework.boot spring-boot-starter-data-jpa org.springframework.boot spring-boot-starter-web org.springframework.cloud spring-cloud-starter-netflix-eureka-client org.springframework.cloud spring-cloud-starter-openfeign org.project.lombok lombok org.hsqldb hsqldb
创建主类OrderService:
@Servicepublic class OrderService { // 依赖注入其他服务和数据库} 通过_post_请求调用order-service的REST API:
POST http://localhost:9002/api/order-service/orders
请求体:
{ "userId": 1, "productId": 1} 响应示例:
{ "id": 1, "productName": "iPhone4", "userName": "Zeus", "price": 99, "createdTime": "2018-08-27T12:17:02.406+0000"} 本文通过一个电商中的常见业务场景——创建订单,展示了如何使用微服务架构进行构建。通过理论与实践的结合,可以更好地理解微服务架构的优势和应用场景。实际开发中,业务场景的复杂性会显著增加,但通过本文的方法,可以为复杂场景提供参考。
转载地址:http://xhqfk.baihongyu.com/