在微服务架构中,系统被拆分为许多独立的服务,每个服务专注于一个业务功能。虽然这种架构提供了高可扩展性和灵活性,但也带来了复杂性,例如服务之间的通信、负载均衡、安全性等问题。因此,设计模式的应用显得尤为重要。
本文将探讨在微服务架构中常用的设计模式,特别是 API 网关、服务注册与发现,并结合示例说明如何实现这些模式。
API 网关是一个集中式的入口,所有外部客户端的请求都通过它进入微服务系统。它的主要职责是:
API 网关是微服务架构中不可或缺的一部分,尤其在客户端需要调用多个服务时。
api-gateway/ // API 网关服务
user-service/ // 用户服务
order-service/ // 订单服务
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-gatewayartifactId>
dependency>
在 application.yml
中配置路由规则:
spring:
cloud:
gateway:
routes:
- id: user-service
uri: http://localhost:8081
predicates:
- Path=/users/**
- id: order-service
uri: http://localhost:8082
predicates:
- Path=/orders/**
server:
port: 8080
http://gateway-service/users/123
。http://localhost:8081/users/123
。在微服务架构中,服务实例通常是动态变化的(扩缩容、服务重启等),因此需要一种机制来动态跟踪服务的地址和端口。这就是服务注册与发现模式的目的。
服务注册与发现通常由以下角色组成:
eureka-server/ // 服务注册中心
user-service/ // 用户服务
order-service/ // 订单服务
添加依赖:
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-netflix-eureka-serverartifactId>
dependency>
在 application.yml
中启用 Eureka 服务:
spring:
application:
name: eureka-server
server:
port: 8761
eureka:
client:
register-with-eureka: false
fetch-registry: false
在主类中添加注解:
@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}
在 user-service
和 order-service
的 application.yml
中配置 Eureka 客户端:
spring:
application:
name: user-service
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
主类启用 Eureka 客户端:
@SpringBootApplication
@EnableEurekaClient
public class UserServiceApplication {
public static void main(String[] args) {
SpringApplication.run(UserServiceApplication.class, args);
}
}
通过 RestTemplate 或 Feign 客户端调用其他服务:
@FeignClient(name = "order-service")
public interface OrderServiceClient {
@GetMapping("/orders/{id}")
Order getOrder(@PathVariable("id") String id);
}
在实际的微服务架构中,API 网关和服务注册与发现通常会结合使用。例如:
http://api-gateway/orders/123
。order-service
的实例地址。order-service
的实例,返回订单信息。通过合理应用这些模式,可以显著提升微服务架构的健壮性和可扩展性。