ASP.NET Core微服务之基于Steeltoe使用Spring Cloud Config统一管理配置

本文涉及的产品
MSE Nacos 企业版免费试用,1600元额度,限量50份
云原生网关 MSE Higress,422元/月
服务治理 MSE Sentinel/OpenSergo,Agent数量 不受限
简介: 本文极简地介绍了一下Spring Cloud Config,并快速构建了一个用于演示的Config Server,然后通过Steeltoe OSS提供的Config客户端将ASP.NET Core与Spring Cloud Config进行集成,最后进行了验证能够正常地从Config Server中获取最新的配置内容。

Tip: 此篇已加入.NET Core微服务基础系列文章

一、关于Spring Cloud Config

  在分布式系统中,每一个功能模块都能拆分成一个独立的服务,一次请求的完成,可能会调用很多个服务协调来完成,为了方便服务配置文件统一管理,更易于部署、维护,所以就需要分布式配置中心组件了,在Spring Cloud中,就有这么一个分布式配置中心组件 — Spring Cloud Config。

  Spring Cloud Config 为分布式系统中的外部配置提供服务器和客户端支持。使用Config Server,我们可以为所有环境中的应用程序管理其外部属性。它非常适合spring应用,也可以使用在其他语言的应用上。随着应用程序通过从开发到测试和生产的部署流程,我们可以管理这些环境之间的配置,并确定应用程序具有迁移时需要运行的一切。服务器存储后端的默认实现使用git,因此它轻松支持标签版本的配置环境,以及可以访问用于管理内容的各种工具。

  Spring Cloud Config的原理图大致如下图(此图来自mazen1991)所示:

  我们将配置文件放入git或者svn等服务中,通过一个Config Server服务来获取git中的配置数据,而我们需要使用的到配置文件的Config Client系统可以通过Config Server来获取对应的配置。

二、快速构建Config Server

  示例版本:Spring Boot 1.5.15.RELEASE,Spring Cloud Edgware.SR3

  (1)添加Spring Cloud Config相关依赖包

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <!-- 热启动,热部署依赖包,为了调试方便,加入此包 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>

        <!-- spring cloud config -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-config-server</artifactId>
        </dependency>
    </dependencies>

    <!-- spring cloud dependencies -->
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Edgware.SR3</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
AI 代码解读

  (2)启动类添加注解

@SpringBootApplication
@EnableConfigServer
public class ConfigServiceApplication {
    public static void main(String[] args) {
        SpringApplication.run(ConfigServiceApplication.class, args);
    }
}
AI 代码解读

  (3)Config相关配置项

server:
  port: 8888

spring:
  application:
    name: config-server
  cloud:
    config:
      server:
        git:
          # 配置Git仓库地址
          uri: https://github.com/EdisonChou/Microservice.PoC.Steeltoe
          # 配置搜索目录
          search-paths: config
          # Git仓库账号(如果需要认证)
          username:
          # Git仓库密码(如果需要认证)
          password:
AI 代码解读

  这里我在GitHub中(https://github.com/EdisonChou/Microservice.PoC.Steeltoe/config目录中)放了一个sample-service-foo.properties的配置文件,里面只有两行内容:

info.profile=default-1.0
info.remarks=this is a remarks of default profile
AI 代码解读

  此外,对于Spring Cloud Config,端点与配置文件的映射规则如下:

/{application}/{profile}[/{label}]
/{application}-{profile}.yml
/{label}/{application}-{profile}.yml
/{application}-{profile}.properties
/{label}/{application}-{profile}.properties
其中,application: 表示微服务的虚拟主机名,即配置的spring.application.name
profile: 表示当前的环境,dev, test or production?
label: 表示git仓库分支,master or relase or others repository name? 默认是master

三、ASP.NET Core中集成Config Server

  (1)快速准备一个ASP.NET Core WebAPI项目(示例版本:2.1),这里以上一篇示例代码中的AgentService为例

  (2)通过NuGet安装Config相关包:

PM>Install-Package Steeltoe.Extensions.Configuration.ConfigServerCore

  (3)改写Program类

    public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .AddConfigServer()  // Add config server via steeltoe
                .UseUrls("http://*:8010")
                .UseStartup<Startup>();
    }
AI 代码解读

  (3)改写Starup类

   public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddOptions();
            // Add Steeltoe Discovery Client service client
            services.AddDiscoveryClient(Configuration);
            // Add Steeltoe Config Client service container
            services.AddConfiguration(Configuration);
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            // Add Configuration POCO 
            services.Configure<ConfigServerData>(Configuration);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMvc();
            // Add Steeltoe Discovery Client service
            app.UseDiscoveryClient();
        }
    }
AI 代码解读

  (4)为自定义配置内容封装一个类

    public class ConfigServerData
    {
        public Info Info { get; set; }
    }

    public class Info
    {
        public string Profile { get; set; }
        public string Remarks { get; set; }
    }
AI 代码解读

  对应:info.profile 以及 info.remarks

  (5)改写Controller,通过依赖注入获取Config内容

    [Route("api/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        private IOptionsSnapshot<ConfigServerData> IConfigServerData { get; set; }

        private IConfigurationRoot Config { get; set; }

        public ValuesController(IConfigurationRoot config, IOptionsSnapshot<ConfigServerData> configServerData)
        {
            if (configServerData != null)
            {
                IConfigServerData = configServerData;
            }

            Config = config;
        }

        [HttpGet]
        [Route("/refresh")]
        public IActionResult Refresh()
        {
            if (Config != null)
            {
                Config.Reload();
            }

            return Ok("Refresh Config Successfully!");
        }

        // GET api/values
        [HttpGet]
        public ActionResult<IEnumerable<string>> Get()
        {
            var config = IConfigServerData.Value;
            return new string[] { $"Profile : {config.Info.Profile}",
                $"Remarks : {config.Info.Remarks}" };
        }
    }
AI 代码解读

  这里提供了一个刷新Config的方法Refresh,由于在没有借助消息总线的情况下,Config Server的Config刷新之后不会推送到各个Config Client,因此需要各个Config Client手动Refresh一下,如下图所示: 

  这里也提一下Spring Cloud Config推荐的刷新配置的方式,即集成Spring Cloud Bus,如下图所示:

  从上图中我们可以看出,它将Config Server加入消息总线之中,并使用Config Server的/bus/refersh端点来实现配置的刷新(一个观察者模式的典型应用)。这样,各个微服务只需要关注自身的业务逻辑,而无需再自己手动刷新配置。但是,遗憾的是,Pivotal目前在Steeltoe中还没有为.NET应用程序提供Spring Cloud Bus的集成,不过可以研究其机制,通过消息队列的客户端如RabbitMQ.Client去自己定制响应事件。

四、快速验证

  (1)从Config Server中获取sampleservice-foo.properties配置文件

  (2)启动AgentService,验证是否能从ConfigServer获取到正确的配置内容

  (3)修改配置文件的属性值:info.profile改为default-1.1

  (4)验证Config Server是否已经获取到最新的info.profile

  (5)手动刷新AgentService的Config对象

  (6)验证是否能够获取最新的info.profile

五、小结

  本文极简地介绍了一下Spring Cloud Config,并快速构建了一个用于演示的Config Server,然后通过Steeltoe OSS提供的Config客户端将ASP.NET Core与Spring Cloud Config进行集成,最后进行了验证能够正常地从Config Server中获取最新的配置内容。当然,关于Spring Cloud Config的内容还有许多,如果要真正使用Spring Cloud Config还需要考虑如何实现自动刷新的问题。从Spring Cloud Config与Apollo的使用体验上来说,本人是更加喜欢Apollo的,无论是功能的全面性和使用的体验来说,Apollo更胜一筹,而且国内的落地案例也更多。因此,如果项目中需要使用或集成统一配置中心,Apollo会是首选。

示例代码

  Click => https://github.com/EdisonChou/Microservice.PoC.Steeltoe/tree/master/src/Chapter3-ConfigServer

参考资料

Steeltoe官方文档:《Steeltoe Doc

Steeltoe官方示例:https://github.com/SteeltoeOSS/Samples

蟋蟀,《.NET Core 微服务架构 Steeltoe的使用

周立,《Spring Cloud与Docker 微服务架构实战

mazhen1991,《使用Spring Cloud Config来统一管理配置文件

冰与火IAF,《Spring Cloud:分布式配置中心 Config

目录
打赏
0
0
0
0
36
分享
相关文章
|
4月前
|
微服务——SpringBoot使用归纳——Spring Boot集成 Swagger2 展现在线接口文档——Swagger2 的配置
本文介绍了在Spring Boot中配置Swagger2的方法。通过创建一个配置类,添加`@Configuration`和`@EnableSwagger2`注解,使用Docket对象定义API文档的详细信息,包括标题、描述、版本和包路径等。配置完成后,访问`localhost:8080/swagger-ui.html`即可查看接口文档。文中还提示了可能因浏览器缓存导致的问题及解决方法。
146 0
微服务——SpringBoot使用归纳——Spring Boot集成 Swagger2 展现在线接口文档——Swagger2 的配置
微服务——SpringBoot使用归纳——Spring Boot事务配置管理——Spring Boot 事务配置
本文介绍了 Spring Boot 中的事务配置与使用方法。首先需要导入 MySQL 依赖,Spring Boot 会自动注入 `DataSourceTransactionManager`,无需额外配置即可通过 `@Transactional` 注解实现事务管理。接着通过创建一个用户插入功能的示例,展示了如何在 Service 层手动抛出异常以测试事务回滚机制。测试结果表明,数据库中未新增记录,证明事务已成功回滚。此过程简单高效,适合日常开发需求。
203 0
微服务——SpringBoot使用归纳——Spring Boot中的项目属性配置——少量配置信息的情形
本课主要讲解Spring Boot项目中的属性配置方法。在实际开发中,测试与生产环境的配置往往不同,因此不应将配置信息硬编码在代码中,而应使用配置文件管理,如`application.yml`。例如,在微服务架构下,可通过配置文件设置调用其他服务的地址(如订单服务端口8002),并利用`@Value`注解在代码中读取这些配置值。这种方式使项目更灵活,便于后续修改和维护。
70 0
微服务——SpringBoot使用归纳——Spring Boot集成MyBatis——MyBatis 介绍和配置
本文介绍了Spring Boot集成MyBatis的方法,重点讲解基于注解的方式。首先简述MyBatis作为持久层框架的特点,接着说明集成时的依赖导入,包括`mybatis-spring-boot-starter`和MySQL连接器。随后详细展示了`properties.yml`配置文件的内容,涵盖数据库连接、驼峰命名规范及Mapper文件路径等关键设置,帮助开发者快速上手Spring Boot与MyBatis的整合开发。
240 0
微服务——SpringBoot使用归纳——Spring Boot集成Thymeleaf模板引擎——依赖导入和Thymeleaf相关配置
在Spring Boot中使用Thymeleaf模板,需引入依赖`spring-boot-starter-thymeleaf`,并在HTML页面标签中声明`xmlns:th=&quot;http://www.thymeleaf.org&quot;`。此外,Thymeleaf默认开启页面缓存,开发时建议关闭缓存以实时查看更新效果,配置方式为`spring.thymeleaf.cache: false`。这可避免因缓存导致页面未及时刷新的问题。
107 0
微服务——SpringBoot使用归纳——Spring Boot中的项目属性配置——指定项目配置文件
在实际项目中,开发环境和生产环境的配置往往不同。为简化配置切换,可通过创建 `application-dev.yml` 和 `application-pro.yml` 分别管理开发与生产环境配置,如设置不同端口(8001/8002)。在 `application.yml` 中使用 `spring.profiles.active` 指定加载的配置文件,实现环境快速切换。本节还介绍了通过配置类读取参数的方法,适用于微服务场景,提升代码可维护性。课程源码可从 [Gitee](https://gitee.com/eson15/springboot_study) 下载。
115 0
微服务——SpringBoot使用归纳——Spring Boot中的项目属性配置——少量配置信息的情形
在微服务架构中,随着业务复杂度增加,项目可能需要调用多个微服务。为避免使用`@Value`注解逐一引入配置的繁琐,可通过定义配置类(如`MicroServiceUrl`)并结合`@ConfigurationProperties`注解实现批量管理。此方法需在配置文件中设置微服务地址(如订单、用户、购物车服务),并通过`@Component`将配置类纳入Spring容器。最后,在Controller中通过`@Resource`注入配置类即可便捷使用,提升代码可维护性。
69 0
【Spring开发】—— Spring Core
原文:【Spring开发】—— Spring Core 前言   最近由于一些工作的需要,还有自己知识的匮乏再次翻开spring。正好整理了一下相关的知识,弥补了之前对spring的一些错误认知。
1099 0
|
7天前
|
SpringBoot自动配置的原理是什么?
Spring Boot自动配置核心在于@EnableAutoConfiguration注解,它通过@Import导入配置选择器,加载META-INF/spring.factories中定义的自动配置类。这些类根据@Conditional系列注解判断是否生效。但Spring Boot 3.0后已弃用spring.factories,改用新格式的.imports文件进行配置。
51 0
AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等