Spring Cloud 专题-配置篇(2)

关注微信公众号:IT技术馆 

Spring Cloud 是一个基于 Spring Boot 构建的云应用开发工具集,它为开发人员提供了在分布式系统中快速实现常见模式(如配置管理、服务发现、断路器等)的能力。下面是一个简化的示例,展示如何在 Spring Boot 应用中引入 Spring Cloud 的一些关键组件。

环境准备

确保你的开发环境中安装了以下工具:

  • Java Development Kit (JDK) 8 或更高版本

  • Maven 或 Gradle 构建工具

  • IDE(如 IntelliJ IDEA 或 Eclipse)

创建 Spring Boot 项目

使用 Spring Initializr (https://start.spring.io/) 来创建一个新的 Spring Boot 项目,选择所需的依赖。例如,如果你想开始一个使用 Eureka 作为服务发现和 Ribbon 作为客户端负载均衡的项目,可以勾选以下依赖项:

  • Spring Web

  • Spring Cloud Starter Netflix Eureka Client

  • Spring Cloud Starter OpenFeign (可选,用于声明式的服务调用)

添加依赖

在生成的 pom.xml 文件中,你会看到类似以下的依赖被自动加入:

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

    <!-- Spring Cloud Starter Netflix Eureka Client -->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>

    <!-- Spring Cloud Starter OpenFeign (可选) -->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-openfeign</artifactId>
    </dependency>
</dependencies>

<!-- Spring Cloud Dependency Management -->
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>${spring-cloud.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

配置 Eureka 服务发现

在 src/main/resources/application.yml 或 application.properties 文件中,配置 Eureka 客户端:

spring:
  application:
    name: my-service # 服务名,用于注册到 Eureka

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/
    register-with-eureka: true
    fetch-registry: true

启动类配置

在你的 Spring Boot 应用的主类上添加 @EnableEurekaClient 注解来启用 Eureka 客户端功能:

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

@SpringBootApplication
@EnableEurekaClient
public class MyServiceApplication {


    public static void main(String[ ] args) {

        SpringApplication.run(MyServiceApplication.class, args);
    }
}

示例:服务间调用

如果要从一个服务调用另一个服务,可以使用 Feign(如果添加了相关依赖)进行声明式的服务调用:

首先,定义一个接口:

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

@FeignClient(name = "another-service") // 另一服务的名称
public interface AnotherServiceClient {
    @GetMapping("/api/data/{id}")
    String getDataById(@PathVariable("id") Long id);
}

然后,在需要调用服务的地方注入这个接口并使用:

@RestController
public class MyController {
    
    @Autowired
    private AnotherServiceClient anotherServiceClient;

    @GetMapping("/my-endpoint")
    public String myEndpoint() {
        String data = anotherServiceClient.getDataById(1L);
        return "Data from Another Service: " + data;
    }
}

断路器 Hystrix

为了提高微服务架构的容错能力,Spring Cloud 提供了断路器 Hystrix 的集成。Hystrix 能够阻止服务雪崩效应,通过快速失败机制保护系统,同时提供 fallback 方法以便在服务不可用时返回一个备选响应。

添加依赖

在 pom.xml 中添加 Hystrix 的依赖:

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

在主类或配置类上添加 @EnableCircuitBreaker 注解:

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

@SpringBootApplication
@EnableEurekaClient
@EnableCircuitBreaker
public class MyServiceApplication {
    // ...
}
使用 Hystrix

修改之前的服务调用代码,使用 HystrixCommand:

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;

@RestController
public class MyController {
    
    @Autowired
    private AnotherServiceClient anotherServiceClient;

    @GetMapping("/my-endpoint")
    public String myEndpoint() {
        String data = anotherServiceClient.getDataByIdWithHystrix(1L);
        return "Data from Another Service: " + data;
    }

    // 在 AnotherServiceClient 接口中添加 Hystrix 命令包装
    @HystrixCommand(fallbackMethod = "getDataByIdFallback")
    @GetMapping("/api/data/{id}")
    public String getDataByIdWithHystrix(@PathVariable("id") Long id) {
        // 这里是原有逻辑,假设直接调用远程服务
        return anotherServiceClient.getDataById(id);
    }

    // Fallback 方法
    public String getDataByIdFallback(Long id) {
        return "Fallback response - Service is unavailable";
    }
}

Spring Cloud Config 服务配置中心

Spring Cloud Config 允许你将配置集中管理,从而便于配置的更改和版本控制。

创建配置服务器
  1. 添加依赖到 pom.xml:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-config-server</artifactId>
</dependency>
  1. 配置 application.yml:

spring:
  cloud:
    config:
      server:
        git:
          uri: https://github.com/your-config-repo.git # 配置仓库地址
          search-paths: config-repo # 可选,配置文件的路径前缀
  1. 启用 Config Server:

import org.springframework.cloud.config.server.EnableConfigServer;
// ...

@SpringBootApplication
@EnableConfigServer
public class ConfigServerApplication {
    // ...
}
配置客户端应用
  1. 添加依赖到 pom.xml:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-config</artifactId>
</dependency>
  1. 配置 bootstrap.yml (注意是 bootstrap 不是 application):

spring:
  cloud:
    config:
      uri: http://localhost:8888 # Config Server 地址
      label: master # Git 分支标签
      name: your-service-name # 配置文件名,不包含后缀
      profile: dev # 环境标识
  1. 在服务启动类或配置类上添加 @RefreshScope 注解,使配置动态刷新:

import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.RestController;

@RefreshScope
@RestController
public class MyRestController {
    // ...

总结

通过以上步骤,你已经在 Spring Boot 应用中成功引入了 Spring Cloud,并实现了服务发现和基本的服务间调用。这只是 Spring Cloud 功能的冰山一角,实际应用中还可以探索更多高级功能,如配置中心、断路器、网关等。

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

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

相关文章

结构思考力:让你的思维更有条理

在这个信息爆炸的时代&#xff0c;如何让自己的思维更有条理&#xff0c;更高效地沟通显得尤为重要。最近读了《结构思考力》一书。今天&#xff0c;我想和大家分享一下读后感&#xff0c;从以下几个方面展开&#xff1a;1. 什么是结构思考力及其重要性&#xff1b;2. 为什么要…

JavaScript日期对象、DOM节点操作(查找、增加、克隆、删除)

目录 1. 日期对象2. DOM节点操作2.1 查找节点2.2 增加节点2.3 克隆节点2.4 删除节点 1. 日期对象 实例化日期对象&#xff1a; 获取当前时间: new Date()获取指定时间: new Date(2023-12-1 17:12:08) 日期对象方法: 方法作用说明getFullYear()获得年份获取四位年份getMonth…

设计可持续数据中心的基本要素

在当今的商业环境中&#xff0c;数据处理中心&#xff08;DPC&#xff09;的重要性日益凸显&#xff0c;它们为海量数据提供稳定的存储、处理和传输服务。随着数据处理中心重要性的不断提升&#xff0c;构建一个具有弹性和可靠性的基础设施变得至关重要。本文将深入探讨构建可持…

Qt做群控系统

群控系统顾名思义&#xff0c;一台设备控制多台机器。首先我们来创造下界面。我们通过QT UI设计界面。设计界面如下&#xff1a; 登录界面&#xff1a; 登录界面分为两种角色&#xff0c;一种是管理员&#xff0c;另一种是超级管理员。两种用户的主界面是不同的。通过选中记住…

获取泛型,泛型擦除,TypeReference 原理分析

说明 author blog.jellyfishmix.com / JellyfishMIX - githubLICENSE GPL-2.0 获取泛型&#xff0c;泛型擦除 下图中示例代码是一个工具类用于生成 csv 文件&#xff0c;需要拿到数据的类型&#xff0c;使用反射感知数据类型的字段&#xff0c;来填充表字段名。可以看到泛型…

LabVIEW开发为什么沟通需求非常重要

在LabVIEW开发项目中&#xff0c;需求沟通是项目成功的基石。以下是需求沟通的重要性及其原因&#xff1a; 明确项目目标&#xff1a; 定义清晰的目标&#xff1a;通过与用户的沟通&#xff0c;可以明确项目的目标和范围&#xff0c;确保开发团队理解用户的实际需求&#xff0c…

JavaFX DatePicker

JavaFX DatePicker允许从给定日历中选择一天。DatePicker控件包含一个带有日期字段和日期选择器的组合框。JavaFX DatePicker控件使用JDK8日期时间API。 import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.DatePicker; import j…

SpringBoot的事务注解

SpringBoot的事务注解 在Spring Boot应用中&#xff0c;事务管理是一个关键的部分&#xff0c;尤其是当涉及到数据库操作时。Spring Boot提供了强大的事务管理支持&#xff0c;使得开发人员可以通过简单的注解来控制事务的边界和行为。本文将介绍如何在Spring Boot中使用事务注…

Go - 4.数组和切片

目录 一.引言 二.定义 1.基础定义 2.引申理解 三.实战 1.估算切片的长度与容量 2.切片的切片长度与容量 四.拓展 1.估算切片容量的增长 2.切片底层数组的替换 五.总结 一.引言 本文主要讨论 Go 语言的数组 array 类型和切片 slice 类型。主要从二者的使用方法&…

C++ 65 之 模版的局限性

#include <iostream> #include <cstring> using namespace std;class Students05{ public:string m_name;int m_age;Students05(string name, int age){this->m_name name;this->m_name age;} };// 两个值进行对比的函数 template<typename T> bool …

PCIe学习——重点提纲

PCIe学习-重点提纲 基础知识 计算机架构基础总线系统概述PCI vs PCI-X vs PCIe PCIe 概述 PCIe 的发展历史PCIe 与其他总线的对比PCIe 的优势和应用场景 PCIe 体系结构 PCIe 分层模型 物理层&#xff08;Physical Layer&#xff09;数据链路层&#xff08;Data Link Layer&…

在 KubeSphere 上快速安装和使用 KDP 云原生数据平台

作者简介&#xff1a;金津&#xff0c;智领云高级研发经理&#xff0c;华中科技大学计算机系硕士。加入智领云 8 余年&#xff0c;长期从事云原生、容器化编排领域研发工作&#xff0c;主导了智领云自研的 BDOS 应用云平台、云原生大数据平台 KDP 等产品的开发&#xff0c;并在…

[Java基本语法] 常量变量与运算符

&#x1f338;个人主页:https://blog.csdn.net/2301_80050796?spm1000.2115.3001.5343 &#x1f3f5;️热门专栏:&#x1f355; Collection与数据结构 (92平均质量分)https://blog.csdn.net/2301_80050796/category_12621348.html?spm1001.2014.3001.5482 &#x1f9c0;线程与…

解决Java项目运行时错误:“Command line is too long”

在开发Java应用的过程中&#xff0c;你可能偶尔会遇到“Error running ‘Application’: Command line is too long”的问题。这是因为Java虚拟机&#xff08;JVM&#xff09;在启动时&#xff0c;如果传递给它的类路径&#xff08;classpath&#xff09;过长&#xff0c;超过了…

1080 MOOC期终成绩

solution 输出合格的学生信息&#xff0c;其中所谓合格需要同时满足 在线编程成绩>200总评成绩>60 总评计算方法为 当期中成绩>期末成绩时&#xff0c;总评期中成绩0.4期末成绩0.6否则&#xff0c;总评期末成绩 通过map建立学号和学生信息间的关联&#xff0c;否则直…

YOLOv10改进 | 注意力篇 | YOLOv10引入Polarized Self-Attention注意力机制

1. Polarized Self-Attention介绍 1.1 摘要:像素级回归可能是细粒度计算机视觉任务中最常见的问题,例如估计关键点热图和分割掩模。 这些回归问题非常具有挑战性,特别是因为它们需要在低计算开销的情况下对高分辨率输入/输出的长期依赖性进行建模,以估计高度非线性的像素语…

AI引领数字安全新纪元,下一代身份基础设施如何帮助企业破局?

近日&#xff0c;Open AI正式发布面向未来人机交互范式的全新大模型GPT-4o&#xff0c;具有文本、语音、图像三种模态的理解力&#xff0c;无疑代表着人工智能技术的又一重大跃进。 人工智能技术领域不断创新和发展&#xff0c;为各行各业带来巨大的生产变革和经济增长的同时&…

RockChip Android12 Settings二级菜单

一:概述 本文将针对Android12 Settings的二级菜单System进行说明。 二:System 1、Activity packages/apps/Settings/AndroidManifest.xml <activityandroid:name=".Settings$SystemDashboardActivity"android:label="@string/header_category_system&quo…

关于Hutool的模块使用说明方法

Hutool包含多个模块&#xff0c;每个模块针对特定的功能需求提供支持&#xff1a;• hutool-aop&#xff1a;JDK动态代理封装&#xff0c;为非IOC环境提供切面支持。• hutool-bloomFilter&#xff1a;布隆过滤器&#xff0c;提供基于Hash算法的实现。• hutool-cache&#xff…

Day 26:2288. 价格减免

Leetcode 2288. 价格减免 句子 是由若干个单词组成的字符串&#xff0c;单词之间用单个空格分隔&#xff0c;其中每个单词可以包含数字、小写字母、和美元符号 ‘$’ 。如果单词的形式为美元符号后跟着一个非负实数&#xff0c;那么这个单词就表示一个 价格 。 例如 “$100”、…