Spring Boot 微服务学习涵盖了从 Spring Boot 框架的基础介绍到快速搭建项目、常用注解详解以及与常见技术的整合,帮助开发者快速入门并掌握微服务开发的基本技能。文章还详细介绍了微服务的基础概念和服务间通信的实现方法,提供了故障处理和日志记录的最佳实践。
Spring Boot 微服务学习:从入门到初级实战 Spring Boot 简介Spring Boot 的定义和特点
Spring Boot 是由 Pivotal 团队提供的一个用于简化 Spring 应用初始搭建及开发过程的框架。它能够快速构建独立的、生产级别的 Spring 应用程序。Spring Boot 的主要特点包括:
- 无需配置文件:大多数情况下,Spring Boot 应用程序不需要任何外部配置文件(如 XML 或 Java)。
- 自动配置:Spring Boot 会自动配置应用程序的大多数方面,如数据库连接、WEB 服务器、日志记录等。
- 嵌入式服务器:Spring Boot 可以直接嵌入 Tomcat、Jetty 或 Undertow 服务器,提供“一次打包,随处运行”的功能。
- 起步依赖:通过单一的“起步依赖”(如 spring-boot-starter-web),可以引入一系列常用的依赖项。
- 命令行界面:Spring Boot 提供了一个命令行界面,可以运行和调试 Spring Boot 应用程序。
Spring Boot 的核心优势
- 简化配置:通过约定优于配置的原则,Spring Boot 大大减少了配置文件的数量和复杂度。
- 快速开发:Spring Boot 通过自动配置、起步依赖等特性,可以快速搭建起一个完整的应用。
- 独立运行:Spring Boot 可以打包为独立的可执行 JAR 文件,无需外部容器即可运行。
- 社区支持:Spring Boot 有一个强大的社区支持,有大量的文档和教程可以参考。
Spring Boot 与传统 Spring 的区别
- 配置简化:Spring Boot 通过约定优于配置的原则,减少了 XML 配置文件的使用,简化了配置过程。
- 自动配置:Spring Boot 提供了大量的自动配置支持,而传统 Spring 需要手动配置几乎所有的依赖。
- 起步依赖:Spring Boot 引入了起步依赖的概念,简化了依赖管理。
- 独立运行:Spring Boot 应用可以打包为独立的 JAR 文件,直接通过命令行运行,而传统 Spring 应用通常需要部署到外部容器中。
使用 IDE 创建 Spring Boot 项目
- 下载并安装 IDE:推荐使用 IntelliJ IDEA 或 Eclipse,这两个 IDE 都有很好的 Spring Boot 支持。
- 
创建新项目: - 在 IntelliJ IDEA 中,选择 File -> New -> Project,然后选择Spring Initializr。
- 在 Eclipse 中,选择 File -> New -> Other -> Spring -> Spring Starter Project。
 
- 在 IntelliJ IDEA 中,选择 
- 填写项目信息:
- 输入项目名称、包名等信息。
- 选择 Java 版本,一般选择默认的最新版本。
- 选择 Spring Boot 版本。
- 选择项目模块和依赖项。
 
// 例如,选择 Spring Web 依赖
dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
}- 创建完成后,IDE 会自动下载并导入所需的依赖。
配置项目的基本设置
- 设置应用主类:通常会在 src/main/java目录下创建一个主类,该类使用@SpringBootApplication注解标记。
- 配置 application.properties:该文件位于src/main/resources目录下,用于配置应用的属性,如端口号、数据库连接等。
# application.properties
server.port=8080
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=root- 配置 pom.xml或build.gradle:根据使用的构建工具,配置依赖和插件。
<!-- pom.xml -->
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>
<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>运行第一个 Spring Boot 应用
- 创建控制器:在 src/main/java目录下创建一个控制器类,使用@RestController注解标记。
// src/main/java/com/example/demo/DemoApplication.java
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}
@RestController
class HelloController {
    @GetMapping("/")
    public String hello() {
        return "Hello, World!";
    }
}- 
运行应用:在 IDE 中,右键点击主类并选择 Run,或者使用命令行mvn spring-boot:run或gradle bootRun。
- 访问服务:打开浏览器,访问 http://localhost:8080/,应可以看到输出Hello, World!。
@SpringBootApplication
@SpringBootApplication 是一个组合注解,包含 @Configuration、@EnableAutoConfiguration 和 @ComponentScan。
- @Configuration:定义配置类,可以使用- @Bean为应用注册配置类。
- @EnableAutoConfiguration:启用自动配置。
- @ComponentScan:扫描并注册应用中的组件,如控制器、服务类等。
// 主类
@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}@RestController
@RestController 是 @Controller 和 @ResponseBody 的组合注解,用于定义 REST 控制器。
@RestController
public class HelloController {
    @GetMapping("/")
    public String hello() {
        return "Hello, World!";
    }
}@Service
@Service 用于标记业务逻辑服务类,通常用于实现应用的核心业务逻辑。
@Service
public class UserService {
    // 业务逻辑实现
}@Repository
@Repository 用于标记数据访问层的组件,如数据库操作类。
@Repository
public class UserRepository {
    // 数据库操作方法
}@Component
@Component 是一个泛型的注解,用于标记 Spring 容器中的任意组件,如工具类、枚举类等。
@Component
public class LoggingService {
    // 日志服务方法
}整合 Spring Data JPA
Spring Data JPA 是一个用于简化数据库访问的框架,提供了统一的数据操作接口。
- 添加依赖:在 pom.xml或build.gradle中添加spring-boot-starter-data-jpa依赖。
<!-- pom.xml -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>- 配置数据库:在 application.properties中配置数据库连接信息。
# application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.hibernate.ddl-auto=update- 创建实体类:使用 @Entity注解标记为实体类。
// 实体类
@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    // getter 和 setter 方法
}- 创建仓库接口:继承 JpaRepository,定义数据访问方法。
// 仓库接口
public interface UserRepository extends JpaRepository<User, Long> {
}- 使用仓库接口:在服务类中注入仓库接口,使用仓库方法进行数据操作。
@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;
    public User save(User user) {
        return userRepository.save(user);
    }
}整合 Spring Security
Spring Security 是一个强大的认证和授权框架,用于保护应用的安全性。
- 添加依赖:在 pom.xml或build.gradle中添加spring-boot-starter-security依赖。
<!-- pom.xml -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>- 配置安全策略:在 SecurityConfig类中配置安全策略。
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/admin/**").hasRole("ADMIN")
                .anyRequest().permitAll()
            .and()
            .formLogin()
            .loginPage("/login")
            .permitAll();
    }
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
            .withUser("user").password("password").roles("USER")
            .and()
            .withUser("admin").password("password").roles("ADMIN");
    }
}- 使用登录页面:创建一个简单的登录页面。
<!-- login.html -->
<form action="/login" method="post">
    <label for="username">Username:</label>
    <input type="text" id="username" name="username">
    <label for="password">Password:</label>
    <input type="password" id="password" name="password">
    <input type="submit" value="Login">
</form>- 访问受保护资源:访问 /admin资源时,需要进行用户认证和授权。
整合 MyBatis
MyBatis 是一个优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。
- 添加依赖:在 pom.xml或build.gradle中添加mybatis-spring-boot-starter依赖。
<!-- pom.xml -->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.3</version>
</dependency>- 配置数据库:在 application.properties中配置数据库连接信息。
# application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=root- 创建实体类:使用 @Data注解标记为实体类。
// 实体类
@Data
public class User {
    private Long id;
    private String name;
}- 创建 Mapper 接口:定义 SQL 语句。
// Mapper 接口
public interface UserMapper {
    @Select("SELECT * FROM user WHERE id = #{id}")
    User getUserById(Long id);
}- 使用 Mapper 接口:在服务类中注入 Mapper 接口,使用 Mapper 方法进行数据操作。
@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;
    public User getUserById(Long id) {
        return userMapper.getUserById(id);
    }
}微服务架构介绍
微服务架构是一种软件架构风格,将一个应用拆分为多个小型、独立的服务。每个服务可以独立开发、部署和扩展,提供特定的业务功能。
- 服务独立性:每个微服务拥有独立的代码库、数据存储和部署单元。
- 轻量级通信:服务之间通过 REST API 或消息队列进行通信。
- 可伸缩性:可以通过增加机器数量或调整资源来快速扩展服务。
- 容错性:单个服务的故障不会影响整个应用的运行。
服务发现与注册
服务发现是指微服务之间自动发现彼此位置并进行通信的过程。注册中心负责维护服务列表并提供服务发现功能。
- 注册中心:常见的注册中心有 Eureka、Consul 和 Zookeeper。
- 服务注册:服务启动时向注册中心注册自己的地址信息。
- 服务发现:服务在调用其他服务时,向注册中心查询目标服务的地址信息。
示例:使用 Eureka 进行服务注册与发现
- 添加依赖:在 pom.xml或build.gradle中添加 Eureka 依赖。
<!-- pom.xml -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>- 配置 Eureka 服务器:在 application.properties中配置 Eureka 服务器地址。
# application.properties
spring.cloud.config.discovery.enabled=true
spring.cloud.discovery.enabled=true
spring.application.name=service-name
eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/- 创建服务:在服务中启用 Eureka 客户端。
@EnableEurekaClient
@SpringBootApplication
public class ServiceApplication {
    public static void main(String[] args) {
        SpringApplication.run(ServiceApplication.class, args);
    }
}负载均衡与容错处理
负载均衡用于将请求分发到多个服务实例上,确保请求能够均匀分布,提高系统可用性和性能。
- 负载均衡器:常见的负载均衡器有 Nginx 和 Apache。
- 容错处理:通过心跳检测、超时重试等机制,确保服务间的通信可靠。
示例:使用 Nginx 进行负载均衡
- 安装并配置 Nginx:安装并配置 Nginx,使其能够接收 HTTP 请求并将其分发到多个服务实例。
# nginx.conf
http {
    upstream backend {
        server 192.168.1.1:8080;
        server 192.168.1.2:8080;
    }
    server {
        listen 80;
        location / {
            proxy_pass http://backend;
        }
    }
}- 配置容错处理:在服务中实现心跳检测和超时重试。
@Service
public class UserService {
    private static final int MAX_RETRY_COUNT = 3;
    private static final int TIMEOUT = 5000;
    public User getUserById(Long id) {
        int retryCount = 0;
        while (retryCount < MAX_RETRY_COUNT) {
            try {
                return restTemplate.getForObject("http://localhost:8080/user/{id}", User.class, id);
            } catch (Exception e) {
                retryCount++;
                if (retryCount >= MAX_RETRY_COUNT) {
                    throw new RuntimeException("Failed to fetch user");
                }
            }
        }
        return null;
    }
}创建微服务项目
- 创建服务项目:使用 Spring Initializr 创建一个新的 Spring Boot 项目。
- 配置项目信息:设置项目名称、包名、Spring Boot 版本等信息。
- 添加依赖:选择需要的起步依赖,如 spring-boot-starter-web。
<!-- pom.xml -->
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>实现服务间通信
- 创建服务接口:定义服务接口,如用户服务接口。
// 用户服务接口
public interface UserService {
    User getUserById(Long id);
    User saveUser(User user);
}- 实现服务接口:在服务实现类中实现服务接口。
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserRepository userRepository;
    @Override
    public User getUserById(Long id) {
        return userRepository.findById(id).orElse(null);
    }
    @Override
    public User saveUser(User user) {
        return userRepository.save(user);
    }
}- 调用服务接口:在其他服务中注入服务接口并调用服务方法。
@RestController
public class UserController {
    @Autowired
    private UserService userService;
    @GetMapping("/user/{id}")
    public User getUser(@PathVariable Long id) {
        return userService.getUserById(id);
    }
    @PostMapping("/user")
    public User saveUser(@RequestBody User user) {
        return userService.saveUser(user);
    }
}故障处理与日志记录
- 添加日志配置:在 application.properties中配置日志配置。
# application.properties
logging.level.root=INFO
logging.file.name=spring-boot.log- 记录日志:在服务实现类中使用 @Slf4j注解记录日志。
@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserRepository userRepository;
    @Override
    public User getUserById(Long id) {
        log.info("Getting user with id: {}", id);
        return userRepository.findById(id).orElse(null);
    }
    @Override
    public User saveUser(User user) {
        log.info("Saving user: {}", user);
        return userRepository.save(user);
    }
}- 异常处理:在控制器中添加全局异常处理器。
@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(value = Exception.class)
    public ResponseEntity<String> handleException(Exception ex) {
        log.error("Exception occurred: ", ex);
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("An error occurred");
    }
}
``
通过以上步骤,我们就可以使用 Spring Boot 构建一个简单的微服务应用,实现服务间通信、故障处理和日志记录等功能。 
		 随时随地看视频
随时随地看视频 
				 
				 
				 
				 
				