微服務架構本質上是一個關於"邊界"的哲學問題,而不僅僅是一個技術方案。
每個服務邊界的確立,都是在回答一個基本問題:"什麼應該在一起,什麼應該分離?"這與我們人生中關於人際關係、職業發展的決策何其相似。過度的耦合如同過度依賴的人際關係,讓人失去獨立性;而過度的拆分則像極端個人主義,導致協作成本激增。
如何使用 Java 搭建微服務系統。以下是完整的微服務架構搭建方案:
1. 技術棧選擇
核心框架
- Spring Boot - 快速開發框架
- Spring Cloud - 微服務全家桶
- Spring Cloud Alibaba - 阿里微服務解決方案
服務治理
- Nacos - 服務註冊與配置中心
- Spring Cloud Gateway - API網關
- OpenFeign - 服務間調用
- LoadBalancer - 負載均衡
容錯與監控
- Sentinel - 流量控制與熔斷降級
- Sleuth + Zipkin - 分佈式鏈路追蹤
-
2. 項目結構設計
microservices-system/
├── gateway-service/ # API網關
├── user-service/ # 用户服務
├── order-service/ # 訂單服務
├── product-service/ # 商品服務
├── common/ # 公共模塊
└── pom.xml # 父POM
3. 具體實現步驟
3.1 父工程配置
<?xml version="1.0" encoding="UTF-8"?>
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>microservices-system</artifactId>
<version>1.0.0</version>
<packaging>pom</packaging>
<modules>
<module>gateway-service</module>
<module>user-service</module>
<module>order-service</module>
<module>product-service</module>
<module>common</module>
</modules>
<properties>
<spring-boot.version>2.7.0</spring-boot.version>
<spring-cloud.version>2021.0.3</spring-cloud.version>
<spring-cloud-alibaba.version>2021.0.1.0</spring-cloud-alibaba.version>
</properties>
<dependencyManagement>
<dependencies>
<!-- Spring Boot -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- Spring Cloud -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- Spring Cloud Alibaba -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>${spring-cloud-alibaba.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
</project>
3.2 公共模塊 (common)
// 統一響應對象
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Result<T> {
private Integer code;
private String message;
private T data;
public static <T> Result<T> success(T data) {
return new Result<>(200, "success", data);
}
public static <T> Result<T> error(String message) {
return new Result<>(500, message, null);
}
}
// 全局異常處理
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public Result<String> handleException(Exception e) {
return Result.error(e.getMessage());
}
}
3.3 用户服務 (user-service)
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.2</version>
</dependency>
</dependencies>
application.yml
server:
port: 8081
spring:
application:
name: user-service
cloud:
nacos:
discovery:
server-addr: localhost:8848
config:
server-addr: localhost:8848
file-extension: yaml
datasource:
url: jdbc:mysql://localhost:3306/user_db?useSSL=false
username: root
password: password
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis-plus:
configuration:
map-underscore-to-camel-case: true
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
UserController.java
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/{id}")
public Result<User> getUserById(@PathVariable Long id) {
User user = userService.getById(id);
return Result.success(user);
}
@PostMapping
public Result<User> createUser(@RequestBody User user) {
userService.save(user);
return Result.success(user);
}
@GetMapping
public Result<List<User>> getAllUsers() {
return Result.success(userService.list());
}
}
User.java
@Data
@TableName("users")
public class User {
@TableId(type = IdType.AUTO)
private Long id;
private String username;
private String email;
private String phone;
private Date createTime;
private Date updateTime;
}
3.4 訂單服務 (order-service)
OrderController.java
@RestController
@RequestMapping("/orders")
public class OrderController {
@Autowired
private OrderService orderService;
@Autowired
private UserFeignClient userFeignClient;
@PostMapping
public Result<Order> createOrder(@RequestBody Order order) {
// 調用用户服務驗證用户
Result<User> userResult = userFeignClient.getUserById(order.getUserId());
if (userResult.getCode() != 200) {
throw new RuntimeException("用户不存在");
}
orderService.save(order);
return Result.success(order);
}
@GetMapping("/{id}")
public Result<Order> getOrderById(@PathVariable Long id) {
Order order = orderService.getById(id);
return Result.success(order);
}
}
UserFeignClient.java
@FeignClient(name = "user-service", path = "/users")
public interface UserFeignClient {
@GetMapping("/{id}")
Result<User> getUserById(@PathVariable("id") Long id);
}
3.5 API網關 (gateway-service)
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
</dependencies>
application.yml
server:
port: 8080
spring:
application:
name: gateway-service
cloud:
nacos:
discovery:
server-addr: localhost:8848
gateway:
discovery:
locator:
enabled: true
routes:
- id: user-service
uri: lb://user-service
predicates:
- Path=/api/users/**
filters:
- StripPrefix=1
- id: order-service
uri: lb://order-service
predicates:
- Path=/api/orders/**
filters:
- StripPrefix=1
3.6 配置中心使用
在Nacos中創建 user-service.yaml 配置:
# user-service 特定配置
logging:
level:
com.example: debug
custom:
config: user-service-config
4. 服務註冊與發現
啓動Nacos
# 下載Nacos並啓動
sh startup.sh -m standalone
服務註冊
每個微服務通過 @EnableDiscoveryClient 自動註冊:
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class UserServiceApplication {
public static void main(String[] args) {
SpringApplication.run(UserServiceApplication.class, args);
}
}
5. 熔斷與降級
使用Sentinel
@FeignClient(name = "user-service", fallback = UserFeignClientFallback.class)
public interface UserFeignClient {
// ...
}
@Component
public class UserFeignClientFallback implements UserFeignClient {
@Override
public Result<User> getUserById(Long id) {
return Result.error("用户服務暫時不可用");
}
}
6. 部署與運行
使用Docker Compose
version: '3.8'
services:
nacos:
image: nacos/nacos-server:latest
environment:
- MODE=standalone
ports:
- "8848:8848"
mysql:
image: mysql:8.0
environment:
- MYSQL_ROOT_PASSWORD=password
ports:
- "3306:3306"
7. 監控與運維
鏈路追蹤配置
# application.yml
spring:
sleuth:
sampler:
probability: 1.0
zipkin:
base-url: http://localhost:9411
總結
這個微服務系統提供了:
- 服務註冊發現 - 基於Nacos
- API網關 - 統一入口和路由
- 服務間調用 - 基於OpenFeign
- 配置管理 - 集中式配置
- 熔斷降級 - 基於Sentinel
- 負載均衡 - 基於LoadBalancer
根據實際需求擴展更多功能,如分佈式事務、消息隊列、監控告警等。
微服務技術棧的更新速度已經超過了大多數團隊的實際需求,形成了一種技術的"時尚競賽"。
很多團隊在Spring Cloud、Dubbo、Kubernetes + Istio之間反覆橫跳,卻忽略了最根本的問題:這些技術變革是否真的為業務創造了價值?還是僅僅為了技術人的"簡歷工程"?
最成功的微服務架構,往往不是技術最超前的,而是與團隊能力、業務發展階段最匹配的。技術決策應該是一場理性的價值投資,而不是感性的時尚追逐。
謝謝你看我的文章,既然看到這裏了,如果覺得不錯,隨手點個贊、轉發、在看三連吧,感謝感謝。那我們,下次再見。
您的一鍵三連,是我更新的最大動力,謝謝
山水有相逢,來日皆可期,謝謝閲讀,我們再會
我手中的金箍棒,上能通天,下能探海