百度360必应搜狗淘宝本站头条
当前位置:网站首页 > IT技术 > 正文

在SpringBoot中怎么使用SpringCloud(3)

wptr33 2024-12-07 17:45 12 浏览

在 Spring Boot 中使用 Spring Cloud,主要是通过集成 Spring Cloud 提供的一些功能来构建微服务应用。Spring Cloud 提供了一些有用的组件来支持微服务架构,如服务注册与发现、负载均衡、API 网关、配置管理、断路器等。

下面是如何在 Spring Boot 项目中使用 Spring Cloud 的基本步骤。

1.设置 Spring Boot 项目

首先,确保你已经创建了一个 Spring Boot 项目。你可以使用 Spring Initializr(https://start.spring.io/)来快速生成一个 Spring Boot 项目,选择 Spring Web 和 Spring Boot DevTools 等常见的依赖。

2.添加 Spring Cloud 依赖

在 pom.xml 或 build.gradle 文件中添加 Spring Cloud 相关的依赖。

使用 Maven:

在 pom.xml 文件中,添加 Spring Cloud 相关的依赖,并指定 Spring Cloud 的版本。在 Spring Boot 2.x 和 Spring Cloud 2020.x 版本中,Spring Cloud 提供了一个 BOM(Bill of Materials)来管理依赖的版本。

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>2020.0.4</version> <!-- 选择适合的版本 -->
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<dependencies>
    <!-- 选择你需要的Spring Cloud组件,例如服务注册与发现 -->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-config</artifactId>
    </dependency>

    <!-- Spring Boot Web -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <!-- Spring Boot Actuator(用于监控) -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
</dependencies>

查看全部

使用 Gradle:

dependencyManagement {
    imports {
        mavenBom "org.springframework.cloud:spring-cloud-dependencies:2020.0.4"  // 选择适合的版本
    }
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.cloud:spring-cloud-starter-netflix-eureka-client'
    implementation 'org.springframework.cloud:spring-cloud-starter-config'
    implementation 'org.springframework.boot:spring-boot-starter-actuator'
}

3.启用 Spring Cloud 组件

在 application.properties 或 application.yml 配置文件中启用 Spring Cloud 相关组件的功能。

服务注册与发现:Eureka 客户端

例如,如果你想使用 Eureka 作为服务注册与发现框架,你需要添加 @EnableEurekaClient 注解,并配置 Eureka 的相关属性。

在application.yml中配置 Eureka:

spring:
  application:
    name: my-service
  cloud:
    discovery:
      enabled: true
    eureka:
      client:
        service-url:
          defaultZone: http://localhost:8761/eureka # Eureka 服务器地址

在 Spring Boot 主类上启用 Eureka 客户端:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@SpringBootApplication
@EnableDiscoveryClient  // 启用服务发现功能
public class MyServiceApplication {

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

服务注册与发现:Eureka 服务器

如果你也想启动一个 Eureka 服务器,可以创建另一个 Spring Boot 项目,并配置为 Eureka 服务器。

在application.yml中配置 Eureka 服务器:

server:
  port: 8761
spring:
  application:
    name: eureka-server
  cloud:
    eureka:
      server:
        enable-self-preservation: false  # 禁用自我保护机制(方便开发测试)
      client:
        register-with-eureka: false   # 该应用作为 Eureka 服务器,不注册自己
      instance:
        hostname: localhost

启动 Eureka 服务器:

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

@SpringBootApplication
@EnableEurekaServer  // 启用 Eureka 服务器功能
public class EurekaServerApplication {

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

4.API 网关:Spring Cloud Gateway

如果你想为微服务应用设置一个 API 网关(统一的入口点),你可以使用 Spring Cloud Gateway。它可以帮助你处理请求路由、认证、限流等。

添加依赖:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>

配置 Gateway 路由规则:

在 application.yml 中配置网关路由:

spring:
  cloud:
    gateway:
      routes:
        - id: my-service-route
          uri: lb://MY-SERVICE  # 微服务的名称(Eureka 服务名)
          predicates:
            - Path=/my-service/**  # 以 `/my-service` 开头的请求都会转发到该服务

5.分布式配置管理:Spring Cloud Config

Spring Cloud Config 提供了集中式配置管理服务,允许将配置文件存储在 Git 仓库或文件系统中,微服务应用可以从 Config Server 拉取配置。

配置 Spring Cloud Config 服务器:

  1. 添加 Spring Cloud Config 服务器依赖:
  2. <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-config-server</artifactId> </dependency>
  3. 启动 Config Server:
  4. import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.config.server.EnableConfigServer; @SpringBootApplication @EnableConfigServer // 启用 Config Server public class ConfigServerApplication { public static void main(String[] args) { SpringApplication.run(ConfigServerApplication.class, args); } }
  5. 在 application.yml 中配置 Config Server 的 Git 仓库路径:
  6. spring: cloud: config: server: git: uri: https://github.com/my-repo/config-repo # 配置文件的 Git 仓库地址 search-paths: '{application}' # 按服务名查找配置

配置 Spring Cloud Config 客户端:

  1. 添加 spring-cloud-starter-config 依赖:
  2. <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-config</artifactId> </dependency>
  3. 配置客户端获取配置:
  4. spring: application: name: my-service # 从 Config Server 获取与该名称相关的配置 cloud: config: uri: http://localhost:8888 # Config Server 地址

6.断路器:Hystrix

Spring Cloud 集成了 Netflix Hystrix 作为断路器,用于处理服务间的调用故障。

添加依赖:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>

启用 Hystrix 注解:

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.stereotype.Service;

@Service
public class MyService {

    @HystrixCommand(fallbackMethod = "fallbackMethod")
    public String callExternalService() {
        // 外部服务调用
        return "Success";
    }

    public String fallbackMethod() {
        return "Fallback response";
    }
}

7.启动微服务

  • 启动 Eureka 服务器。
  • 启动服务提供者(如 MyServiceApplication)。
  • 启动 API 网关(如 GatewayApplication),通过网关访问微服务。

通过 Spring Cloud 你可以非常方便地在 Spring Boot 中构建一个完整的微服务架构。通过配置服务发现、负载均衡、API 网关、分布式配置等功能,能够解决许

相关推荐

Git 的设计:版本管理的天才之作

Git的设计之所以被称为“天才”,是因为它通过一系列**革命性的理念**和**精妙的工程实现**,完美解决了版本控制中的核心痛点。以下是其设计精髓的深度解析:---###一、**颠覆传统的核心设计...

IDEA上如何重新设置git账号密码

修改git账号密码,使用IDEA拉取项目的文件,出现如下错误信息。fatal:unabletoaccess'http://192.168.105.101:8901/XX/XX-XX-p...

在IDEA中利用ignore插件忽略Git非必要提交的文件

迎关注我的头条号:Wooola,10年Java软件开发及架构设计经验,专注于Java、Go语言、微服务架构,致力于每天分享原创文章、快乐编码和开源技术。前言在IEDA中,使用Maven建多工程编写代码...

Git入门系列之分支切换完全指南

在Git中切换分支时,若存在未提交的修改,需谨慎处理以避免数据丢失。主要注意事项包括:1)通过gitstatus检查当前修改;2)优先使用gitstash暂存修改再切换;3)可提交修...

解决Git推送提交时&#39;src refspec master does not match any&#39;错误

技术背景在使用Git进行代码管理时,我们经常会遇到各种问题。其中,“srcrefspecmasterdoesnotmatchany”错误是一个比较常见的问题。当我们尝试使用...

修改git提交的用户名

在我们项目中,新手同学们往往由于不当操作导致提交的用户名填写错误,当我们用户名填写错误的时候可以通过命令修改。获取当前用户名:gitconfiguser.name...

在项目管理中,自动关联Git代码提交,集成Gitlab/码云/Git等

不再让开发提交的代码成为“黑洞”在软件开发过程中,会有一个问题和担心,就是不知道开发人员提交的代码质量如何,规范怎样。更为让人痛苦的莫过于当时某个功能需求改了什么代码,根本无人知道。今天,分享一个工具...

常用的十五个Git命令汇总?

Git是一个分布式的版本管理系统,在开发中被广泛应用于代码版本的管理,下面就是在日常开发中常用的一些Git命令以及其示例操作,如下所示,我们就来一起看看吧!gitinit用于初始化一个新的Git仓库...

git修改已提交记录的用户信息

背景介绍因为使用的是个人电脑,配置的git全局config的用户信息是和github的账户一致的。新下载的工作git,由于没有单独设置局部的用户信息,导致提交记录使用的是github用户,在push代...

刚来公司,大佬让我Git下 我该怎么办?

我们在开发过程中,都会用到版本控制工具。常用的工具有SVNGIt等。但现在越来越多的人喜欢用Git。本文为你介绍新手如何快速上手Git。创建自己的远程仓库远程仓库,顾名思义。就是将自己的代码放到远程服...

腾讯自研Git客户端,助力每个人都可以轻松使用Git

...

Git+Maven+Sonar实现提交代码前进行代码的质量检查

Git+Maven+Sonar实现提交代码前进行代码的质量检查一、前言为了规范代码质量,使开发人员写出更高质量的代码,实践了一下git-hooks中的pre-commit钩子,可以在提交代码时强制校验...

Git Rebase

本文档将深入讨论gitrebase命令。Rebase命令在设置仓库和重写历史页面中也有涉及。本页将更详细地介绍gitrebase的配置和执行。这里将涵盖常见的Rebase使用场景和注...

Git提交规范

一、分区存储...

git合并分支时禁止合并特定文件

问题:1.在日常开发过程中经常会遇到多环境,但是环境文件不同的情况,导致每次切换git环境时候非常麻烦,可能会提交上来不需要提交的文件,一个文件来回提交修改。场景:...