Spring Boot 和 Spring Cloud 微服务开发实践详解

昨天没有及时更,先说声抱歉,今后不会了

对今天的讲解,大家可以看一下《Spring Boot 和 Spring Cloud 微服务开发实践》这本书,大学图书馆应该都有的,我觉得非常不错,很详细

那就进入今天的正题

随着云计算和互联网技术的快速发展,微服务架构逐渐成为构建大型分布式应用的标准方法之一。Spring Boot 和 Spring Cloud 是实现微服务架构的流行框架,它们共同为企业提供了构建高效、可扩展和可维护的微服务应用的强大工具。

本文将通过具体的案例,详细讲解如何使用 Spring Boot 和 Spring Cloud 构建微服务应用。

下一篇博客,我将通过一个具体的例子------一个在线购物系统,来展示如何使用 Spring Boot 和 Spring Cloud 构建一个完整的微服务架构。

1. Spring Boot 和 Spring Cloud 简介

Spring Boot 是一个基于 Spring 框架的快速开发工具,它的设计目标是简化新 Spring 应用的初始搭建以及开发过程。Spring Boot 通过自动配置、嵌入式服务器、以及对外部配置的支持,使得开发者可以快速构建出独立的、生产级别的基于 Spring 框架的应用程序。

Spring Cloud 是基于 Spring Boot 实现的一系列框架的集合,旨在解决分布式系统中的常见问题,如服务发现、配置管理、断路器、API 网关等。Spring Cloud 为开发者提供了一套完整的微服务解决方案,使得构建微服务架构变得更加简单和高效。

如果大家都忘了,可以看看我之前写的这两篇博客

1、详细且系统的Spring Boot应用开发https://blog.csdn.net/speaking_me/article/details/143189480

2、一次性全讲清楚!Spring Cloud微服务

https://blog.csdn.net/speaking_me/article/details/143349732

2. 构建基础的 Spring Boot 应用

假设我们要构建一个简单的用户管理服务,我们将使用 Spring Boot 创建一个 RESTful API。以下是详细的步骤:

步骤 1:创建 Spring Boot 项目

使用 Spring Initializr 创建一个新的 Spring Boot 项目,选择以下依赖:

  • Spring Web
  • Spring Boot DevTools
  • Lombok

创建完成后,项目结构如下:

复制代码
user-service
├── src
│   ├── main
│   │   ├── java
│   │   │   └── com.example.userservice
│   │   │       ├── controller
│   │   │       │   └── UserController.java
│   │   │       ├── model
│   │   │       │   └── User.java
│   │   │       ├── repository
│   │   │       │   └── UserRepository.java
│   │   │       ├── service
│   │   │       │   └── UserService.java
│   │   │       └── UserServiceApplication.java
│   │   └── resources
│   │       └── application.properties
│   └── test
│       └── java
│           └── com.example.userservice
│               └── UserServiceApplicationTests.java
└── pom.xml

步骤 2:编写用户实体

model 包下创建 User.java 文件:

复制代码
package com.example.userservice.model;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    private Long id;
    private String name;
    private String email;
}

步骤 3:编写用户仓库

repository 包下创建 UserRepository.java 文件:

复制代码
package com.example.userservice.repository;

import com.example.userservice.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}

步骤 4:编写用户服务

service 包下创建 UserService.java 文件:

复制代码
package com.example.userservice.service;

import com.example.userservice.model.User;
import com.example.userservice.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    public List<User> getAllUsers() {
        return userRepository.findAll();
    }

    public User getUserById(Long id) {
        return userRepository.findById(id).orElse(null);
    }

    public User createUser(User user) {
        return userRepository.save(user);
    }

    public User updateUser(Long id, User userDetails) {
        User user = userRepository.findById(id).orElse(null);
        if (user != null) {
            user.setName(userDetails.getName());
            user.setEmail(userDetails.getEmail());
            return userRepository.save(user);
        }
        return null;
    }

    public void deleteUser(Long id) {
        userRepository.deleteById(id);
    }
}

步骤 5:编写用户控制器

controller 包下创建 UserController.java 文件:

复制代码
package com.example.userservice.controller;

import com.example.userservice.model.User;
import com.example.userservice.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping
    public List<User> 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 userDetails) {
        return userService.updateUser(id, userDetails);
    }

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

步骤 6:配置应用

resources 目录下的 application.properties 文件中添加以下配置:

复制代码
spring.datasource.url=jdbc:mysql://localhost:3306/userdb
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update

步骤 7:启动应用

UserServiceApplication.java 文件中启动应用:

复制代码
package com.example.userservice;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

3. 配置服务发现

为了实现服务发现,我们将使用 Spring Cloud Eureka。以下是配置步骤:

步骤 1:创建 Eureka 服务注册中心

创建一个新的 Spring Boot 项目,选择以下依赖:

  • Spring Web
  • Spring Cloud Starter Netflix Eureka Server

修改 pom.xml 文件,添加 Spring Cloud 版本管理:

复制代码
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>Hoxton.SR12</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

在主类中添加 @EnableEurekaServer 注解:

复制代码
package com.example.eurekaserver;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

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

application.properties 文件中配置 Eureka 服务注册中心:

复制代码
server.port=8761
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false

步骤 2:配置用户服务

在用户服务项目中添加 Eureka 客户端依赖:

复制代码
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>

application.properties 文件中配置 Eureka 客户端:

复制代码
spring.application.name=user-service
eureka.client.service-url.defaultZone=http://localhost:8761/eureka/

4. 配置中心

为了更好地管理配置,我们可以使用 Spring Cloud Config。以下是配置步骤:

步骤 1:创建配置中心

创建一个新的 Spring Boot 项目,选择以下依赖:

  • Spring Web
  • Spring Cloud Config Server

在主类中添加 @EnableConfigServer 注解:

复制代码
package com.example.configserver;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.config.server.EnableConfigServer;

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

application.properties 文件中配置 Config Server:

复制代码
server.port=8888
spring.profiles.active=native
spring.cloud.config.server.native.search-locations=file:/config-repo/

步骤 2:配置用户服务

在用户服务项目中添加 Config Client 依赖:

复制代码
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-config</artifactId>
</dependency>

bootstrap.properties 文件中配置 Config Client:

复制代码
spring.application.name=user-service
spring.cloud.config.uri=http://localhost:8888

5. 断路器

为了提高系统的稳定性,我们可以使用 Hystrix 作为断路器。以下是配置步骤:

步骤 1:添加 Hystrix 依赖

在用户服务项目中添加 Hystrix 依赖:

复制代码
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>

步骤 2:配置 Hystrix

在主类中添加 @EnableCircuitBreaker 注解:

复制代码
package com.example.userservice;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;

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

在用户服务中使用 @HystrixCommand 注解:

复制代码
package com.example.userservice.controller;

import com.example.userservice.model.User;
import com.example.userservice.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.circuitbreaker.CircuitBreakerFactory;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private CircuitBreakerFactory circuitBreakerFactory;

    @GetMapping
    public List<User> getAllUsers() {
        return circuitBreakerFactory.create("getAllUsers").run(
                () -> userService.getAllUsers(),
                throwable -> Collections.emptyList()
        );
    }

    @GetMapping("/{id}")
    public User getUserById(@PathVariable Long id) {
        return circuitBreakerFactory.create("getUserById").run(
                () -> userService.getUserById(id),
                throwable -> null
        );
    }

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

    @PutMapping("/{id}")
    public User updateUser(@PathVariable Long id, @RequestBody User userDetails) {
        return userService.updateUser(id, userDetails);
    }

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

6. API 网关

为了统一管理微服务之间的交互,我们可以使用 Spring Cloud Gateway 作为 API 网关。以下是配置步骤:

步骤 1:创建 API 网关

创建一个新的 Spring Boot 项目,选择以下依赖:

  • Spring Web
  • Spring Cloud Gateway
  • Spring Cloud Starter Netflix Eureka Discovery

在主类中添加 @EnableDiscoveryClient 注解:

复制代码
package com.example.gateway;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableDiscoveryClient;

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

application.properties 文件中配置 Gateway:

复制代码
server.port=8080
spring.application.name=gateway-service
eureka.client.service-url.defaultZone=http://localhost:8761/eureka/
spring.cloud.gateway.routes[0].id=user-service
spring.cloud.gateway.routes[0].uri=lb://user-service
spring.cloud.gateway.routes[0].predicates[0]=Path=/users/**

7. 总结

通过上述实践,我们详细讲解了如何使用 Spring Boot 和 Spring Cloud 构建一个简单的用户管理微服务应用。在这个过程中,我们使用了 Spring Boot 来快速创建和配置微服务,使用 Spring Cloud Eureka 实现了服务发现,使用 Spring Cloud Config 管理配置,使用 Hystrix 实现了断路器,最后使用 Spring Cloud Gateway 统一管理微服务之间的交互。

这些工具和技术的结合,不仅简化了微服务的开发和部署,还提高了系统的可扩展性和稳定性。

相关推荐
白仑色2 小时前
Spring Cloud Gateway 实战指南
spring boot·微服务·路由转发·限流熔断
Sylvia-girl3 小时前
Java——抽象类
java·开发语言
Touper.6 小时前
Redis 基础详细介绍(Redis简单介绍,命令行客户端,Redis 命令,Java客户端)
java·数据库·redis
m0_535064606 小时前
C++模版编程:类模版与继承
java·jvm·c++
虾条_花吹雪7 小时前
Using Spring for Apache Pulsar:Message Production
java·ai·中间件
tomorrow.hello7 小时前
Java并发测试工具
java·开发语言·测试工具
Moso_Rx7 小时前
javaEE——synchronized关键字
java·java-ee
张小洛7 小时前
Spring AOP 是如何生效的(入口源码级解析)?
java·后端·spring
DKPT8 小时前
Java设计模式之行为型模式(观察者模式)介绍与说明
java·笔记·学习·观察者模式·设计模式
追风少年浪子彦8 小时前
mapstruct与lombok冲突原因及解决方案
java·spring boot·spring·spring cloud