【SpringBoot】SpringBoot:打造现代化微服务架构

文章目录

      • 引言
      • 微服务架构概述
        • 什么是微服务架构
        • 微服务的优势
      • 使用SpringBoot构建微服务
        • 创建SpringBoot微服务项目
          • 示例:创建订单服务
        • 配置数据库
        • 创建实体类和Repository
        • 创建服务层和控制器
      • 微服务间通信
        • 使用RestTemplate进行同步通信
          • 示例:调用用户服务
        • 使用Feign进行声明式通信
          • 示例:使用Feign调用用户服务
      • 服务发现与注册
        • 配置Eureka Server
        • 配置Eureka Client
      • API网关
      • 配置管理
        • 配置Spring Cloud Config Server
        • 配置Spring Cloud Config Client
      • 服务监控与管理
        • 使用Spring Boot Actuator进行监控
        • 使用Spring Cloud Sleuth进行分布式跟踪
      • 结论

在这里插入图片描述

引言

在当今的软件开发环境中,微服务架构已经成为一种主流趋势。微服务架构的核心思想是将应用程序分解为一组小的、自治的服务,每个服务负责单一的业务功能。这种架构的优势在于其灵活性、可扩展性和易于维护性。SpringBoot作为一个强大的框架,为开发现代化微服务架构提供了极大的便利。本文将详细探讨如何使用SpringBoot来构建和管理微服务。

微服务架构概述

什么是微服务架构

微服务架构是一种设计风格,它将应用程序划分为一组小型、独立部署的服务。这些服务可以独立开发、测试、部署和扩展。每个微服务通常负责特定的业务功能,并通过轻量级的通信协议(通常是HTTP/REST或消息队列)进行交互。

微服务的优势
  • 模块化:将应用程序分解为多个独立的模块,使得每个模块可以独立开发和部署。
  • 灵活性:不同的微服务可以使用不同的技术栈和数据库,适应不同的业务需求。
  • 可扩展性:可以独立地扩展每个微服务,根据业务需求进行水平扩展。
  • 故障隔离:一个微服务的故障不会影响到整个系统,提高了系统的可靠性。

使用SpringBoot构建微服务

创建SpringBoot微服务项目

使用SpringBoot创建微服务项目非常简单。通过Spring Initializr,开发者可以快速生成一个包含基本配置的SpringBoot项目。

示例:创建订单服务
  1. 访问 Spring Initializr,选择合适的项目选项(如Maven项目、Java语言、Spring Boot版本等)。
  2. 添加必要的依赖项,如Spring Web、Spring Data JPA、H2 Database等。
  3. 生成项目并下载到本地。

解压下载的项目,并导入到IDE中。

配置数据库

application.properties文件中配置H2数据库:

spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.h2.console.enabled=true
创建实体类和Repository

创建一个订单实体类:

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Order {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String product;
    private Integer quantity;
    private Double price;

    // getters and setters
}

创建一个OrderRepository接口:

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface OrderRepository extends JpaRepository<Order, Long> {
}
创建服务层和控制器

服务层:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class OrderService {

    @Autowired
    private OrderRepository orderRepository;

    public List<Order> getAllOrders() {
        return orderRepository.findAll();
    }

    public Order getOrderById(Long id) {
        return orderRepository.findById(id).orElse(null);
    }

    public Order createOrder(Order order) {
        return orderRepository.save(order);
    }

    public void deleteOrder(Long id) {
        orderRepository.deleteById(id);
    }
}

控制器:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/orders")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @GetMapping
    public List<Order> getAllOrders() {
        return orderService.getAllOrders();
    }

    @GetMapping("/{id}")
    public Order getOrderById(@PathVariable Long id) {
        return orderService.getOrderById(id);
    }

    @PostMapping
    public Order createOrder(@RequestBody Order order) {
        return orderService.createOrder(order);
    }

    @DeleteMapping("/{id}")
    public void deleteOrder(@PathVariable Long id) {
        orderService.deleteOrder(id);
    }
}

微服务间通信

在微服务架构中,各个服务需要通过某种方式进行通信。常见的通信方式包括HTTP RESTful API和消息队列。SpringBoot提供了多种工具和框架来简化微服务间的通信。

使用RestTemplate进行同步通信

RestTemplate是Spring提供的一个同步HTTP客户端,用于向其他服务发起HTTP请求。

示例:调用用户服务

假设我们有一个用户服务(User Service),需要在订单服务中调用用户服务来获取用户信息。

  1. 创建一个RestTemplate Bean:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class AppConfig {

    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}
  1. 在OrderService中使用RestTemplate:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class OrderService {

    @Autowired
    private RestTemplate restTemplate;

    public User getUserById(Long userId) {
        String url = "http://localhost:8081/users/" + userId;
        return restTemplate.getForObject(url, User.class);
    }
}
使用Feign进行声明式通信

Feign是一个声明式HTTP客户端,它使得HTTP调用变得更加简单和直观。Spring Cloud集成了Feign,使其与SpringBoot应用无缝结合。

示例:使用Feign调用用户服务
  1. 添加Feign依赖:
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
  1. 启用FeignClient:
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableFeignClients
public class AppConfig {
}
  1. 创建Feign客户端接口:
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

@FeignClient(name = "user-service", url = "http://localhost:8081")
public interface UserClient {

    @GetMapping("/users/{id}")
    User getUserById(@PathVariable("id") Long id);
}
  1. 在OrderService中使用Feign客户端:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class OrderService {

    @Autowired
    private UserClient userClient;

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

服务发现与注册

在微服务架构中,服务的数量可能会动态变化。为了管理这些服务,可以使用服务发现与注册机制。Spring Cloud提供了Eureka作为服务发现与注册的解决方案。

配置Eureka Server
  1. 创建Eureka Server项目并添加依赖:
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
  1. 启用Eureka Server:
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);
    }
}
  1. 配置Eureka Server:
server.port=8761
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
配置Eureka Client

在每个微服务中,添加Eureka Client依赖并进行配置。

  1. 添加依赖:
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
  1. 配置Eureka Client:
eureka.client.service-url.defaultZone=http://localhost:8761/eureka/
  1. 启用Eureka Client:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

@SpringBootApplication
@EnableEurekaClient
public class OrderServiceApplication {

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

通过Eureka,微服务可以自动注册和发现其他服务,从而简化了服务间的通信和管理。

API网关

在微服务架构中,API网关是一个关键组件。它充当所有客户端请求的入口,并将请求路由到相应的微服务。Spring Cloud Gateway是一个高效的API网关解决方案。

配置Spring Cloud Gateway

  1. 创建API网关项目并添加依赖:
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
  1. 配置路由:
spring.cloud.gateway.routes[0].id=order-service
spring.cloud.gateway.routes[0].uri=http://localhost:8080
spring.cloud.gateway.routes[0].predicates[0]=Path=/orders/**
  1. 启动API网关:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ApiGatewayApplication {

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

通过API网关,所有客户端请求将通过统一入口,从而简化了客户端与微服务的交互。

配置管理

在微服务架构中,每个服务可能有不同的配置需求。为了统一管理配置,可以使用Spring Cloud Config。

配置Spring Cloud Config Server
  1. 创建Config Server项目并添加依赖:
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-config-server</artifactId>
</dependency>
  1. 启用Config Server:
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);
    }
}
  1. 配置Config Server:
server.port=8888
spring.cloud.config.server.git.uri=https://github.com/your-repo/config-repo
配置Spring Cloud Config Client

在每个微服务中,添加Config Client依赖并进行配置。

  1. 添加依赖:
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-config</artifactId>
</dependency>
  1. 配置Config Client:
spring.cloud.config.uri=http://localhost:8888

通过Spring Cloud Config,可以集中管理和分发配置文件,提高配置管理的效率和一致性。

服务监控与管理

微服务架构需要有效的监控和管理机制。Spring Boot Actuator和Spring Cloud Sleuth是两种常用的工具,用于监控和分布式跟踪。

使用Spring Boot Actuator进行监控

Spring Boot Actuator提供了一系列的端点,用于监控和管理Spring Boot应用。

  1. 添加Actuator依赖:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
  1. 启用Actuator端点:
management.endpoints.web.exposure.include=*

通过访问/actuator端点,可以获取应用的各种监控信息,如健康检查、指标、环境等。

使用Spring Cloud Sleuth进行分布式跟踪

Spring Cloud Sleuth为Spring Boot应用提供了分布式跟踪功能,帮助开发者了解请求在微服务中的传播路径。

  1. 添加Sleuth依赖:
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-sleuth</artifactId>
</dependency>
  1. 配置Sleuth:
spring.sleuth.sampler.probability=1.0

通过Spring Cloud Sleuth,可以追踪每个请求的调用链,帮助识别性能瓶颈和故障点。

结论

SpringBoot通过其简化配置、自动化和强大的生态系统,显著提升了微服务架构的开发效率。无论是创建微服务、实现服务间通信、管理配置还是进行服务监控,SpringBoot和Spring Cloud都提供了丰富的工具和解决方案。通过合理利用这些工具和框架,开发者可以构建出高性能、可扩展和易维护的现代化微服务架构。希望这篇文章能够帮助开发者更好地理解和使用SpringBoot,在实际项目中取得成功。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/730850.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

用智能插件(Fitten Code: Faster and Better AI Assistant)再次修改vue3 <script setup>留言板

<template><div><button class"openForm" click"openForm" v-if"!formVisible">编辑</button><button click"closeForm" v-if"formVisible">取消编辑</button><hr /><formv-i…

手把手教你java CPU飙升300%如何优化

背景 今天有个项目运行一段时间后&#xff0c;cpu老是不堪负载。 排查 top 命令 TOP 命令 top t 按cpu 排序 top m 按内存使用率排序 从上面看很快看出是 pid 4338 这个进程资源消耗很高。 top -Hp pid top -Hp 4338 找到对应线程消耗的资源shftp cpu占用进行排序&#xf…

优维“态势感知监控”产品:像“上帝”一样掌控应用系统

什么是态势感知&#xff1f; 态势感知是一种基于环境的、动态、整体地洞悉全网安全风险的能力。它以安全大数据为基础&#xff0c;从全局视角对全网安全威胁进行发现识别、理解分析展示和响应处置&#xff0c;并预测发展趋势&#xff0c;为后续网络安全的相关决策与行动提供数据…

Redis 7.x 系列【4】命令手册

有道无术&#xff0c;术尚可求&#xff0c;有术无道&#xff0c;止于术。 本系列Redis 版本 7.2.5 源码地址&#xff1a;https://gitee.com/pearl-organization/study-redis-demo 文章目录 1. 说明2. 命令手册2.1 Generic2.2 数据类型2.2.1 String2.2.2 Hash2.2.3 List2.2.4 S…

JavaScript--函数的参数列表以及arguments的用法

函数声明时&#xff0c;参数的问题 即使函数在定义时没有显示声明任何参数&#xff0c;你仍然可以在调用该函数时传递参数。 这是因为 JavaScript 函数内部有一个隐含的 arguments 对象&#xff0c;它包含了所有传递给函数的参数。 示例 我们来通过一些示例代码来更清楚地说…

拒绝零散碎片, 一文理清MySQL的各种锁

系列文章目录 学习MySQL先有全局观&#xff0c;细说其发展历程及特点 Mysql常用操作&#xff0c;谈谈排序与分页 拒绝零散碎片&#xff0c; 一文理清MySQL的各种锁&#xff08;收藏向&#xff09; 系列文章目录一、MySQL的锁指什么二、排他与共享三、全局锁&#xff08;Global…

PhotoShop批量生成存储jpg

1、说明 根据之前自动批量生成psd格式的文件。打印一般都是jpg格式的&#xff0c;那如果将这些psd的文件&#xff0c;生成jpg&#xff0c;本文采用ps的动作 2、生成动作 点击窗口-动作 录屏存储jpg动作 3、根据动作生成 选择相应动作之后选择需要处理的文件夹

Aidlux 1.4 部署Nextcloud 2024.6实录 没成功

Aidux阉割版Debain10&#xff0c;坑很多&#xff0c;比如找不到实际的系统日志&#xff0c;有知道的大神吗&#xff1f; 1 Apache2安装 # 测试Apache2 sudo apt update && sudo apt upgrade sudo apt install apache2 -y80端口疑似被禁止只能换端口 rootlocalhost:/…

定制化智能硬件解决方案:为您的业务量身打造的未来之选

在这个数字化转型的时代&#xff0c;企业必须适应快速变化的技术需求和激烈的市场竞争。定制化智能硬件解决方案提供了一种独特的方法&#xff0c;使企业能够通过优化流程和提高效率来满足其特定的业务需求。本文将探讨定制化智能硬件如何助力企业实现卓越性能和创新&#xff0…

mongosh常用命令详解及如何开启MongoDB身份验证

目录 Mongosh常用命令介绍 连接到MongoDB实例 基本命令 查看当前数据库 切换数据库 查看所有数据库 查看当前数据库中的集合 CRUD操作 插入文档 查询文档 更新文档 删除文档 替换文档 索引操作 创建索引 查看索引 删除索引 聚合操作 数据库管理 创建用户 …

计算机毕业设计Python+Vue.js知识图谱音乐推荐系统 音乐爬虫可视化 音乐数据分析 大数据毕设 大数据毕业设计 机器学习 深度学习 人工智能

开发技术 协同过滤算法、机器学习、LSTM、vue.js、echarts、django、Python、MySQL 创新点协同过滤推荐算法、爬虫、数据可视化、LSTM情感分析、短信、身份证识别 补充说明 适合大数据毕业设计、数据分析、爬虫类计算机毕业设计 介绍 音乐数据的爬取&#xff1a;爬取歌曲、…

(项目实战)业务场景中学透RocketMQ5.0-事务消息在预付卡系统中的应用

1 什么是事务消息 RocketMQ中事务消息主要是解决分布式场景下各业务系统事务一致性问题&#xff0c;常见的分布式事务解决方案有传统XA事务方案、TCC、本地消息表、MQ事务等。今天我们基于RocketMQ事务消息解决预付卡系统资金账户子系统和会员积分子系统、短信子系统分布式事务…

JMeter的基本使用与性能测试,完整入门篇保姆式教程

Jmeter 的简介 JMeter是一个纯Java编写的开源软件&#xff0c;主要用于进行性能测试和功能测试。它支持测试的应用/服务/协议包括Web (HTTP, HTTPS)、SOAP/REST Webservices、FTP、Database via JDBC等。我们最常使用的是HTTP和HTTPS协议。 Jmeter主要组件 线程组&#xff08…

永辉超市:胖东来爆改,成色几何?

单日业绩暴涨14倍。来&#xff0c;看看&#xff0c;这是被胖东来爆改后重新开业后的门店&#xff0c; 不出意外的流量爆炸。胖东来爆改&#xff0c;真是解决实体商超困境的灵丹妙药吗&#xff1f; 今天我们聊聊——永辉超市 最近两年实体商超日子都不好过&#xff0c;去年13家…

在Worpress增加网站的二级目录,并转向到站外网站

在WordPress中&#xff0c;你可以通过添加自定义重定向来实现将某个二级目录&#xff08;例如 www.example.com/subdir&#xff09;重定向到站外网站。可以通过以下几种方法来实现&#xff1a; 方法一&#xff1a;使用 .htaccess 文件 如果你的服务器使用Apache&#xff0c;你…

使用上海云盾 CDN 和 CloudFlare 后 Nginx、 WordPress、 Typecho 获取访客真实 IP 方法

最近因为被 DDoS/CC 攻击的厉害,明月就临时的迁移了服务器,原来的服务器就空置下来了,让明月有时间对服务器进行了重置重新部署安装生产环境。因为站点同时使用了上海云盾和 CloudFlare(具体思路可以参考【国内网站使用国外 CloudFlare CDN 的思路分享】一文)两个 CDN 服务…

Java数据类型与运算符

1. 变量和类型 变量指的是程序运行时可变的量&#xff0c;相当于开辟一块空间来保存一些数据。 类型则是对变量的种类进行了划分&#xff0c;不同类型的变量具有不同的特性。 1.1 整型变量&#xff08;重点&#xff09; 基本语法格式&#xff1a; int 变量名 初始值;代码示…

20240621在飞凌的OK3588-C开发板linux系统的CAM3上接OV5645录像

20240621在飞凌的OK3588-C开发板linux系统的CAM3上接OV5645录像 2024/6/21 19:57 开发板&#xff1a;OK3588-C SDK&#xff1a;linux R4/Buildroot v4l2-ctl --list-devices v4l2-ctl --list-formats-ext -d /dev/video16 gst-launch-1.0 v4l2src device/dev/video16 num-bu…

【Git】 -- Part2 -- 分支管理

1. 分支 在 Git 中&#xff0c;分支&#xff08;Branch&#xff09;是用于在项目中创建独立开发线路的机制。分支使得开发者可以在不影响主干&#xff08;main 或 master&#xff09;的情况下进行实验、开发新功能或修复 Bug。 举个例子&#xff1a; 分⽀就好像是科幻电影⾥⾯…

鸿蒙开发:【进程模型概述】

进程模型概述 系统的进程模型如下图所示&#xff1a; 应用中&#xff08;同一包名&#xff09;的所有PageAbility、ServiceAbility、DataAbility、FormAbility运行在同一个独立进程中&#xff0c;即图中绿色部分的“Main Process”。 WebView拥有独立的渲染进程&#xff0c;即…