1. 首页 > IT综合教程 > 正文

IT教程FG412-微服务架构

内容大纲

1. 微服务架构概述

微服务架构是一种将单一应用程序分解为一组小型服务的架构风格,每个服务运行在自己的进程中,通过轻量级机制(通常是HTTP API)进行通信。每个服务都是独立部署、独立扩展的,可以使用不同的编程语言和数据库。

微服务架构的核心优势包括:

  • 独立部署和扩展
  • 技术栈灵活性
  • 故障隔离
  • 团队自治
  • 快速迭代

学习交流加群风哥微信: itpux-com

2. 微服务设计原则

2.1 单一职责原则

每个微服务应该只负责一个业务功能,做到高内聚、低耦合。服务的边界应该清晰,避免服务之间的依赖和耦合。

2.2 服务拆分原则

  • 按业务能力拆分
  • 按子域拆分
  • 按团队结构拆分
  • 按数据边界拆分

2.3 服务设计最佳实践

# 微服务设计最佳实践
1. 服务粒度
– 服务应该足够小,便于理解和维护
– 服务应该足够大,具有独立的业务价值
– 避免纳米服务和巨型服务

2. 服务边界
– 基于业务能力定义服务边界
– 使用领域驱动设计(DDD)识别边界上下文
– 每个服务拥有独立的数据存储

3. 服务接口
– 使用清晰的API契约
– 版本化API接口
– 向后兼容的变更

4. 服务自治
– 独立部署和扩展
– 独立的数据存储
– 独立的技术栈选择

5. 服务治理
– 统一的配置管理
– 统一的服务发现
– 统一的监控和日志

风哥风哥提示:微服务设计的关键是找到合适的服务边界,既要避免服务过大导致耦合,又要避免服务过小导致复杂性增加。

3. 服务通信

3.1 RESTful API通信

# Spring Boot RESTful API示例
// 用户服务Controller
@RestController
@RequestMapping(“/api/users”)
public class UserController {

@Autowired
private UserService userService;

@GetMapping
public List getAllUsers() {
return userService.getAllUsers();
}

@GetMapping(“/{id}”)
public User getUserById(@PathVariable Long id) {
return userService.getUserById(id);
}

@PostMapping
public User createUser(@RequestBody User user) {
return userService.createUser(user);
}

@PutMapping(“/{id}”)
public User updateUser(@PathVariable Long id, @RequestBody User user) {
return userService.updateUser(id, user);
}

@DeleteMapping(“/{id}”)
public void deleteUser(@PathVariable Long id) {
userService.deleteUser(id);
}
}

// 使用RestTemplate调用服务
@Service
public class OrderService {

@Autowired
private RestTemplate restTemplate;

public User getUser(Long userId) {
String url = “http://user-service/api/users/” + userId;
return restTemplate.getForObject(url, User.class);
}
}

// 使用Feign调用服务
@FeignClient(name = “user-service”)
public interface UserClient {

@GetMapping(“/api/users/{id}”)
User getUserById(@PathVariable(“id”) Long id);
}

@Service
public class OrderService {

@Autowired
private UserClient userClient;

public User getUser(Long userId) {
return userClient.getUserById(userId);
}
}

3.2 消息队列通信

# Spring Boot消息队列示例
// RabbitMQ配置
@Configuration
public class RabbitMQConfig {

public static final String ORDER_QUEUE = “order.queue”;
public static final String ORDER_EXCHANGE = “order.exchange”;
public static final String ORDER_ROUTING_KEY = “order.routing.key”;

@Bean
public Queue orderQueue() {
return new Queue(ORDER_QUEUE, true);
}

@Bean
public DirectExchange orderExchange() {
return new DirectExchange(ORDER_EXCHANGE);
}

@Bean
public Binding orderBinding(Queue orderQueue, DirectExchange orderExchange) {
return BindingBuilder.bind(orderQueue).to(orderExchange).with(ORDER_ROUTING_KEY);
}
}

// 消息生产者
@Service
public class OrderProducer {

@Autowired
private RabbitTemplate rabbitTemplate;

public void sendOrderMessage(Order order) {
rabbitTemplate.convertAndSend(
RabbitMQConfig.ORDER_EXCHANGE,
RabbitMQConfig.ORDER_ROUTING_KEY,
order
);
}
}

// 消息消费者
@Service
public class OrderConsumer {

@RabbitListener(queues = RabbitMQConfig.ORDER_QUEUE)
public void processOrder(Order order) {
System.out.println(“Received order: ” + order.getId());
// 处理订单逻辑
}
}

// Kafka配置
@Configuration
public class KafkaConfig {

@Bean
public ProducerFactory producerFactory() {
Map config = new HashMap<>();
config.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, “fgedudb:9092”);
config.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
config.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JsonSerializer.class);
return new DefaultKafkaProducerFactory<>(config);
}

@Bean
public KafkaTemplate kafkaTemplate() {
return new KafkaTemplate<>(producerFactory());
}
}

// Kafka生产者
@Service
public class OrderKafkaProducer {

@Autowired
private KafkaTemplate kafkaTemplate;

public void sendOrder(String topic, Order order) {
kafkaTemplate.send(topic, order);
}
}

// Kafka消费者
@Service
public class OrderKafkaConsumer {

@KafkaListener(topics = “order-topic”, groupId = “order-group”)
public void processOrder(Order order) {
System.out.println(“Received order: ” + order.getId());
// 处理订单逻辑
}
}

更多学习教程www.fgedu.net.cn

4. 服务发现

4.1 Eureka服务发现

# Spring Cloud Eureka服务发现
// Eureka服务器配置
@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}

// application.yml
server:
port: 8761

eureka:
client:
register-with-eureka: false
fetch-registry: false
service-url:
defaultZone: http://fgedudb:8761/eureka/

// 服务提供者配置
@SpringBootApplication
@EnableEurekaClient
public class UserServiceApplication {
public static void main(String[] args) {
SpringApplication.run(UserServiceApplication.class, args);
}
}

// application.yml
server:
port: 8081

spring:
application:
name: user-service

eureka:
client:
service-url:
defaultZone: http://fgedudb:8761/eureka/

// 服务消费者配置
@SpringBootApplication
@EnableDiscoveryClient
public class OrderServiceApplication {
public static void main(String[] args) {
SpringApplication.run(OrderServiceApplication.class, args);
}
}

// application.yml
server:
port: 8082

spring:
application:
name: order-service

eureka:
client:
service-url:
defaultZone: http://fgedudb:8761/eureka/

// 查看Eureka服务列表
$ curl http://fgedudb:8761/eureka/apps

// 输出结果

1
UP_2_

USER-SERVICE

user-service:8081
192.168.1.10
USER-SERVICE
192.168.1.10
UP 8081



ORDER-SERVICE

order-service:8082
192.168.1.11
ORDER-SERVICE
192.168.1.11
UP 8082


4.2 Consul服务发现

# Spring Cloud Consul服务发现
// Consul配置
@SpringBootApplication
@EnableDiscoveryClient
public class UserServiceApplication {
public static void main(String[] args) {
SpringApplication.run(UserServiceApplication.class, args);
}
}

// application.yml
server:
port: 8081

spring:
application:
name: user-service
cloud:
consul:
host: fgedudb
port: 8500
discovery:
service-name: ${spring.application.name}
health-check-path: /actuator/health
health-check-interval: 10s

// 启动Consul
$ consul agent -dev

// 查看Consul服务列表
$ curl http://fgedudb:8500/v1/agent/services

// 输出结果
{
“user-service”: {
“ID”: “user-service”,
“Service”: “user-service”,
“Tags”: [],
“Address”: “192.168.1.10”,
“Port”: 8081,
“Status”: “passing”,
“Checks”: [
{
“Node”: “consul-server”,
“CheckID”: “service:user-service”,
“Name”: “Service ‘user-service’ check”,
“Status”: “passing”
}
]
}
}

author:www.itpux.com

5. API网关

5.1 Spring Cloud Gateway

# Spring Cloud Gateway配置
@SpringBootApplication
@EnableDiscoveryClient
public class GatewayApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayApplication.class, args);
}
}

// application.yml
server:
port: 8080

spring:
application:
name: api-gateway
cloud:
gateway:
discovery:
locator:
enabled: true
lower-case-service-id: true
routes:
– id: user-service
uri: lb://user-service
predicates:
– Path=/api/users/**
filters:
– StripPrefix=1
– name: RequestRateLimiter
args:
redis-rate-limiter.replenishRate: 10
redis-rate-limiter.burstCapacity: 20
– id: order-service
uri: lb://order-service
predicates:
– Path=/api/orders/**
filters:
– StripPrefix=1
– name: CircuitBreaker
args:
name: orderCircuitBreaker
fallbackUri: forward:/fallback

eureka:
client:
service-url:
defaultZone: http://fgedudb:8761/eureka/

// 自定义过滤器
@Component
public class AuthFilter implements GlobalFilter, Ordered {

@Override
public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpRequest request = exchange.getRequest();
String token = request.getHeaders().getFirst(“Authorization”);

if (token == null || !validateToken(token)) {
ServerHttpResponse response = exchange.getResponse();
response.setStatusCode(HttpStatus.UNAUTHORIZED);
return response.setComplete();
}

return chain.filter(exchange);
}

@Override
public int getOrder() {
return -100;
}

private boolean validateToken(String token) {
// 验证token逻辑
return true;
}
}

// 降级处理
@RestController
public class FallbackController {

@GetMapping(“/fallback”)
public String fallback() {
return “Service is temporarily unavailable. Please try again later.”;
}
}

更多学习教程公众号风哥教程itpux_com

6. 配置管理

6.1 Spring Cloud Config

# Spring Cloud Config配置
// Config服务器
@SpringBootApplication
@EnableConfigServer
public class ConfigServerApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigServerApplication.class, args);
}
}

// application.yml
server:
port: 8888

spring:
application:
name: config-server
cloud:
config:
server:
git:
uri: https://github.com/fgedu/config-repo
search-paths: config
username: git-username
password: git-password

// Config客户端配置
@SpringBootApplication
@EnableDiscoveryClient
public class UserServiceApplication {
public static void main(String[] args) {
SpringApplication.run(UserServiceApplication.class, args);
}
}

// bootstrap.yml
spring:
application:
name: user-service
cloud:
config:
uri: http://fgedudb:8888
profile: dev
label: main

// 配置文件示例
// user-service-dev.yml
server:
port: 8081

spring:
datasource:
url: jdbc:mysql://fgedudb:3306/user_db
username: root
password: password

// 访问配置
$ curl http://fgedudb:8888/user-service/dev

// 输出结果
{
“name”: “user-service”,
“profiles”: [“dev”],
“label”: null,
“version”: “abc123def456”,
“state”: null,
“propertySources”: [
{
“name”: “https://github.com/fgedu/config-repo/config/user-service-dev.yml”,
“source”: {
“server.port”: 8081,
“spring.datasource.url”: “jdbc:mysql://fgedudb:3306/user_db”,
“spring.datasource.username”: “root”,
“spring.datasource.password”: “password”
}
}
]
}

6.2 Apollo配置中心

# Apollo配置中心
// Apollo客户端配置
@SpringBootApplication
@EnableApolloConfig
public class UserServiceApplication {
public static void main(String[] args) {
SpringApplication.run(UserServiceApplication.class, args);
}
}

// application.yml
app:
id: user-service

apollo:
meta: http://fgedudb:8080
bootstrap:
enabled: true
namespaces: application

// 使用配置
@Service
public class UserService {

@Value(“${user.max.count:100}”)
private int maxUserCount;

@ApolloConfig
private Config config;

public int getMaxUserCount() {
return config.getIntProperty(“user.max.count”, 100);
}

@ApolloConfigChangeListener
public void onChange(ConfigChangeEvent changeEvent) {
ConfigChange change = changeEvent.getChange(“user.max.count”);
System.out.println(“Config changed: ” + change.getOldValue() + ” -> ” + change.getNewValue());
}
}

风哥风哥提示:配置管理是微服务架构的重要组成部分,需要确保配置的集中管理和动态更新。

7. 熔断与降级

7.1 Hystrix熔断器

# Spring Cloud Hystrix配置
@SpringBootApplication
@EnableCircuitBreaker
public class OrderServiceApplication {
public static void main(String[] args) {
SpringApplication.run(OrderServiceApplication.class, args);
}
}

// 使用Hystrix
@Service
public class OrderService {

@Autowired
private UserClient userClient;

@HystrixCommand(
fallbackMethod = “getUserFallback”,
commandProperties = {
@HystrixProperty(name = “execution.isolation.thread.timeoutInMilliseconds”, value = “3000”),
@HystrixProperty(name = “circuitBreaker.requestVolumeThreshold”, value = “10”),
@HystrixProperty(name = “circuitBreaker.errorThresholdPercentage”, value = “50”),
@HystrixProperty(name = “circuitBreaker.sleepWindowInMilliseconds”, value = “5000”)
}
)
public User getUser(Long userId) {
return userClient.getUserById(userId);
}

public User getUserFallback(Long userId) {
User user = new User();
user.setId(userId);
user.setName(“Default User”);
return user;
}
}

// Hystrix Dashboard配置
@SpringBootApplication
@EnableHystrixDashboard
public class HystrixDashboardApplication {
public static void main(String[] args) {
SpringApplication.run(HystrixDashboardApplication.class, args);
}
}

// application.yml
server:
port: 7979

hystrix:
dashboard:
proxy-stream-allow-list: “*”

7.2 Resilience4j熔断器

# Resilience4j配置
// application.yml
resilience4j:
circuitbreaker:
configs:
default:
slidingWindowSize: 10
slidingWindowType: COUNT_BASED
failureRateThreshold: 50
waitDurationInOpenState: 5s
permittedNumberOfCallsInHalfOpenState: 3
instances:
userService:
baseConfig: default
ratelimiter:
configs:
default:
limitForPeriod: 10
limitRefreshPeriod: 1s
timeoutDuration: 0
instances:
userService:
baseConfig: default
retry:
configs:
default:
maxAttempts: 3
waitDuration: 1s
instances:
userService:
baseConfig: default

// 使用Resilience4j
@Service
public class OrderService {

@Autowired
private UserClient userClient;

@CircuitBreaker(name = “userService”, fallbackMethod = “getUserFallback”)
@RateLimiter(name = “userService”)
@Retry(name = “userService”)
public User getUser(Long userId) {
return userClient.getUserById(userId);
}

public User getUserFallback(Long userId, Exception e) {
User user = new User();
user.setId(userId);
user.setName(“Default User”);
return user;
}
}

学习交流加群风哥QQ113257174

8. 分布式事务

8.1 Seata分布式事务

# Seata分布式事务配置
// Seata配置
@SpringBootApplication
@EnableDiscoveryClient
@EnableAutoDataSourceProxy
public class OrderServiceApplication {
public static void main(String[] args) {
SpringApplication.run(OrderServiceApplication.class, args);
}
}

// application.yml
server:
port: 8082

spring:
application:
name: order-service
datasource:
url: jdbc:mysql://fgedudb:3306/order_db
username: root
password: password

seata:
enabled: true
application-id: order-service
tx-service-group: my_tx_group
registry:
type: nacos
nacos:
server-addr: fgedudb:8848
namespace: “”
group: SEATA_GROUP
config:
type: nacos
nacos:
server-addr: fgedudb:8848
namespace: “”
group: SEATA_GROUP

// 使用分布式事务
@Service
public class OrderService {

@Autowired
private OrderMapper orderMapper;

@Autowired
private UserClient userClient;

@GlobalTransactional(name = “create-order”, rollbackFor = Exception.class)
public void createOrder(Order order) {
// 创建订单
orderMapper.insert(order);

// 扣减用户余额
userClient.deductBalance(order.getUserId(), order.getAmount());

// 如果扣减余额失败,订单会自动回滚
}
}

8.2 分布式事务最佳实践

  • 尽量避免分布式事务
  • 使用最终一致性
  • 实施幂等性设计
  • 使用补偿机制
  • 监控事务状态

9. 监控与日志

9.1 分布式追踪

# Spring Cloud Sleuth配置
// application.yml
spring:
application:
name: user-service
sleuth:
sampler:
probability: 1.0
zipkin:
base-url: http://fgedudb:9411

// 日志配置
logging:
level:
org.springframework.web.servlet.DispatcherServlet: DEBUG
pattern:
level: “%5p [${spring.application.name:},%X{traceId:-},%X{spanId:-}]”

// 日志输出示例
2026-04-03 10:00:00.000 DEBUG [user-service,abc123def456,ghi789jkl012] 12345 — [nio-8081-exec-1] o.s.web.servlet.DispatcherServlet : GET “/api/users/1”, parameters={}

// Zipkin配置
@SpringBootApplication
@EnableZipkinServer
public class ZipkinServerApplication {
public static void main(String[] args) {
SpringApplication.run(ZipkinServerApplication.class, args);
}
}

// application.yml
server:
port: 9411

spring:
application:
name: zipkin-server

9.2 ELK日志收集

# ELK日志收集配置
// Logback配置


fgedudb:5000

{“app_name”:”user-service”}




// Logstash配置
input {
tcp {
port => 5000
codec => json_lines
}
}

filter {
if [app_name] {
mutate {
add_field => { “index_name” => “%{app_name}-%{+YYYY.MM.dd}” }
}
}
}

output {
elasticsearch {
hosts => [“fgedudb:9200”]
index => “%{index_name}”
}
}

// Kibana查询示例
app_name: “user-service” AND level: “ERROR”

10. 最佳实践

10.1 微服务架构最佳实践

  • 合理拆分服务边界
  • 使用API网关统一入口
  • 实施服务发现机制
  • 配置熔断和降级策略
  • 使用分布式配置管理
  • 建立完善的监控体系
  • 实施分布式追踪
  • 自动化部署和运维

10.2 服务设计最佳实践

  • 单一职责原则
  • 清晰的API契约
  • 版本化API接口
  • 幂等性设计
  • 容错性设计

10.3 服务通信最佳实践

  • 选择合适的通信协议
  • 实施服务发现
  • 配置负载均衡
  • 使用熔断和降级
  • 监控服务调用
生产环境风哥建议:

  • 合理规划服务边界,避免过度拆分
  • 建立完善的服务治理体系
  • 实施自动化部署和运维
  • 建立完善的监控和告警体系
  • 定期评估和优化架构
  • 培训团队成员的微服务技能
  • 建立文档和知识库
  • 持续改进和优化

author:www.itpux.com

本文由风哥教程整理发布,仅用于学习测试使用,转载注明出处:http://www.fgedu.net.cn/10327.html

联系我们

在线咨询:点击这里给我发消息

微信号:itpux-com

工作日:9:30-18:30,节假日休息