Skip to content

微服务基础

随着互联网应用的复杂性不断增加,传统的单体架构逐渐暴露出诸多问题。微服务架构作为一种新兴的架构模式,通过将大型应用拆分为多个小型、独立的服务,有效解决了单体应用的扩展性和维护性问题。本章节将介绍微服务的基础概念和Spring Boot框架的使用。

什么是微服务?

微服务是一种架构模式,它将单一应用程序开发为一组小型服务,每个服务运行在自己的进程中,并使用轻量级机制(通常是HTTP资源API)进行通信。这些服务围绕业务能力构建,并可以通过全自动部署机制独立部署。

微服务的特点

  1. 单一职责:每个服务只关注一个特定的业务功能
  2. 独立部署:每个服务可以独立部署和扩展
  3. 去中心化:每个服务可以使用不同的技术栈
  4. 容错性:单个服务的故障不会影响整个系统
  5. 可扩展性:可以根据需求独立扩展特定服务

微服务 vs 单体架构

特性单体架构微服务架构
部署整体部署独立部署
扩展性整体扩展按需扩展
技术栈统一技术栈多样化技术栈
开发复杂度相对简单相对复杂
维护性随着规模增长变差每个服务相对简单

Spring Boot框架

Spring Boot是Spring框架的一个扩展,旨在简化Spring应用的初始搭建以及开发过程。它通过提供默认配置和自动配置功能,让开发者能够快速构建独立的、生产级别的Spring应用。

Spring Boot优势

  1. 快速开发:提供开箱即用的配置
  2. 内嵌服务器:内置Tomcat、Jetty等服务器
  3. 自动配置:根据类路径自动配置Spring应用
  4. 生产就绪:提供健康检查、指标监控等功能
  5. 无代码生成:不生成额外代码

创建Spring Boot项目

使用Spring Initializr

Spring Initializr是创建Spring Boot项目的官方工具,可以通过网页或IDE插件使用。

  1. 访问 https://start.spring.io/
  2. 选择项目类型(Maven/Gradle)
  3. 选择语言(Java/Kotlin/Groovy)
  4. 选择Spring Boot版本
  5. 填写项目元数据(Group、Artifact等)
  6. 选择所需依赖(Web、JPA、MySQL等)
  7. 点击"Generate"下载项目

项目结构

src
├── main
│   ├── java
│   │   └── com
│   │       └── example
│   │           └── demo
│   │               └── DemoApplication.java
│   └── resources
│       ├── application.properties
│       └── static
└── test
    └── java
        └── com
            └── example
                └── demo
                    └── DemoApplicationTests.java

Spring Boot核心注解

@SpringBootApplication

@SpringBootApplication是Spring Boot应用的核心注解,它是一个组合注解,包含了:

  1. @Configuration:标识该类为配置类
  2. @EnableAutoConfiguration:启用自动配置
  3. @ComponentScan:启用组件扫描
java
@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

@RestController

@RestController@Controller@ResponseBody的组合注解,用于创建RESTful Web服务。

java
@RestController
@RequestMapping("/api/users")
public class UserController {
    
    @GetMapping("/{id}")
    public User getUser(@PathVariable Long id) {
        // 返回用户信息
        return new User(id, "张三");
    }
    
    @PostMapping
    public User createUser(@RequestBody User user) {
        // 创建用户
        return user;
    }
}

@Service、@Repository、@Component

这些注解用于标识不同类型的组件:

java
@Service
public class UserService {
    // 业务逻辑
}

@Repository
public class UserRepository {
    // 数据访问
}

@Component
public class UtilityClass {
    // 工具类
}

配置管理

application.properties

Spring Boot使用application.propertiesapplication.yml文件进行配置:

properties
# 服务器配置
server.port=8080
server.servlet.context-path=/api

# 数据库配置
spring.datasource.url=jdbc:mysql://localhost:3306/myapp
spring.datasource.username=root
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

# JPA配置
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect

配置类

java
@Configuration
public class AppConfig {
    
    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

数据访问

Spring Data JPA

Spring Data JPA简化了数据访问层的开发:

java
@Entity
@Table(name = "users")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    
    @Column(nullable = false)
    private String username;
    
    @Column(nullable = false)
    private String email;
    
    // 构造函数、getter和setter省略
}

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
    Optional<User> findByUsername(String username);
    List<User> findByEmailContaining(String email);
}

@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;
    
    public List<User> getAllUsers() {
        return userRepository.findAll();
    }
    
    public User getUserById(Long id) {
        return userRepository.findById(id)
                .orElseThrow(() -> new UserNotFoundException("用户不存在"));
    }
    
    public User createUser(User user) {
        return userRepository.save(user);
    }
}

RESTful API设计

REST(Representational State Transfer)是一种软件架构风格,用于设计网络应用的API。

REST原则

  1. 资源标识:每个资源都有唯一的URI
  2. 统一接口:使用标准HTTP方法(GET、POST、PUT、DELETE)
  3. 无状态:每个请求都包含处理所需的所有信息
  4. 可缓存:响应可以被缓存
  5. 分层系统:客户端不需要知道是否直接连接到服务器

HTTP方法映射

HTTP方法CRUD操作示例
GET读取GET /api/users
POST创建POST /api/users
PUT更新PUT /api/users/1
DELETE删除DELETE /api/users/1

异常处理

java
@RestControllerAdvice
public class GlobalExceptionHandler {
    
    @ExceptionHandler(UserNotFoundException.class)
    public ResponseEntity<ErrorResponse> handleUserNotFound(UserNotFoundException ex) {
        ErrorResponse error = new ErrorResponse("USER_NOT_FOUND", ex.getMessage());
        return ResponseEntity.status(HttpStatus.NOT_FOUND).body(error);
    }
    
    @ExceptionHandler(Exception.class)
    public ResponseEntity<ErrorResponse> handleGenericException(Exception ex) {
        ErrorResponse error = new ErrorResponse("INTERNAL_ERROR", "服务器内部错误");
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
    }
}

public class UserNotFoundException extends RuntimeException {
    public UserNotFoundException(String message) {
        super(message);
    }
}

public class ErrorResponse {
    private String code;
    private String message;
    
    public ErrorResponse(String code, String message) {
        this.code = code;
        this.message = message;
    }
    
    // getter和setter省略
}

微服务核心组件

服务注册与发现

在微服务架构中,服务实例的动态性要求有服务注册与发现机制。

Eureka Server

java
@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {
    public static void main(String[] args) {
        SpringApplication.run(EurekaServerApplication.class, args);
    }
}

Eureka Client

java
@SpringBootApplication
@EnableEurekaClient
public class UserServiceApplication {
    public static void main(String[] args) {
        SpringApplication.run(UserServiceApplication.class, args);
    }
}

配置中心

配置中心用于集中管理微服务的配置信息。

Spring Cloud Config Server

java
@SpringBootApplication
@EnableConfigServer
public class ConfigServerApplication {
    public static void main(String[] args) {
        SpringApplication.run(ConfigServerApplication.class, args);
    }
}

API网关

API网关是微服务架构中的入口点,负责请求路由、负载均衡、认证授权等功能。

Spring Cloud Gateway

java
@SpringBootApplication
@EnableDiscoveryClient
public class GatewayApplication {
    public static void main(String[] args) {
        SpringApplication.run(GatewayApplication.class, args);
    }
}

配置:

yaml
spring:
  cloud:
    gateway:
      routes:
        - id: user-service
          uri: lb://user-service
          predicates:
            - Path=/api/users/**

实践练习

创建一个简单的用户管理系统微服务:

  1. 使用Spring Boot创建用户服务
  2. 实现用户信息的增删改查API
  3. 使用Spring Data JPA操作数据库
  4. 添加异常处理机制
  5. 集成Eureka实现服务注册与发现
  6. 使用Spring Cloud Gateway作为API网关

总结

微服务架构通过将大型应用拆分为小型、独立的服务,有效解决了单体应用的扩展性和维护性问题。Spring Boot作为构建微服务的重要框架,大大简化了Java应用的开发过程。

通过本章节的学习,你应该掌握了:

  1. 微服务的基本概念和优势
  2. Spring Boot的核心特性和使用方法
  3. RESTful API的设计原则
  4. 微服务架构中的核心组件

在后续章节中,我们将深入学习分布式系统的相关技术,包括分布式事务、消息队列、缓存等。