4

微服务系列之Api文档 swagger整合 - CL静淡

 1 year ago
source link: https://www.cnblogs.com/saltlight-wangchao/p/16723080.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

微服务系列之Api文档 swagger整合

1.前言

 微服务架构随之而来的前后端彻底分离,且服务众多,无论是前后端对接亦或是产品、运营翻看,一个现代化、规范化、可视化、可尝试的文档是多么重要,所以我们这节就说说swagger。

  Swagger是一款RESTFUL接口的文档在线自动生成+功能测试功能软件。Swagger是一个规范和完整的框架,用于生成、描述、调用和可视化RESTful风格的Web服务。目标是使客户端和文件系统作为服务器以同样的速度来更新文件的方法,参数和模型紧密集成到服务器。

  swagger优势:

  1)后端开发人员,不在重复的用wiki或word不断改来改去;

  2).net core集成简单,无侵入性,开发人员只需要使用.net自身的注释即可;

2.实战

  新建一个.net core3.1项目,nuget安装Swashbuckle.AspNetCore包最新版本

 services.AddSwaggerGen(e =>
            {
                e.SwaggerDoc("v1",
                    new Microsoft.OpenApi.Models.OpenApiInfo()
                    {
                        Title = "MySwaggerService1 API",//文档标题
                        Version = "v1"//文档版本
                    }
                    );
                //e.OperationFilter<AddAuthTokenFilter>();
                e.IncludeXmlComments(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "MySwaggerService1.xml"));//swagger会自动生成文档xml文件,指定位置来加载
                //e.IncludeXmlComments(System.IO.Path.Combine(Microsoft.Extensions.PlatformAbstractions.PlatformServices.Default.Application.ApplicationBasePath, "xxxxx.xml"));//注释的这里,swagger会为每个类库都生成类库名.xml的配置文件,我这里只有一个简单的demo,所以不用
            });

添加中间件

app.UseSwagger()
               .UseSwaggerUI(c =>
               {
                   c.SwaggerEndpoint($"/swagger/v1/swagger.json", "MySwaggerService1");
               });

项目右键属性=》生成,将debug和release配置下,输出=》输出路径=》xml文档位置,勾选,默认即可。

846824-20220923154205765-265124058.png

写一个get接口,写一个post接口。

  [Route("api/[controller]")]
    [ApiController]
    public class DemoController : ControllerBase
    {
        /// <summary>
        /// 我的接口
        /// </summary>
        /// <param name="no">我的参数</param>
        /// <returns></returns>
        [ProducesResponseType(typeof(string), (int)HttpStatusCode.OK)]
        [ProducesResponseType(typeof(string), (int)HttpStatusCode.BadRequest)]
        [HttpGet("my")]
        public async Task<IActionResult> My([FromQuery] string no)
        {
            return Ok("hello docker");
        }

        /// <summary>
        /// 我的第二个接口
        /// </summary>
        /// <param name="queryModel"></param>
        /// <returns></returns>
        [ProducesResponseType(typeof(List<MyViewModel>), (int)HttpStatusCode.OK)]
        [ProducesResponseType(typeof(string), (int)HttpStatusCode.BadRequest)]
        [HttpPost("query/my")]
        public async Task<IActionResult> PostMy([FromBody] MyQueryModel queryModel)
        {
            var res = new List<MyViewModel>();
            res.Add(new MyViewModel() { 
                Gid = "1",
                MyList = new List<int>() { 1,2,3}
            });
            return Ok(res);
        }
    }

启动后:地址 http://localhost:xxxx/swagger.

846824-20220923154603703-563682372.png

到此,.net core集成swagger结束。

3.swagger切换

  上文这个服务的在线文档已经好了,如果10个服务的话,想要查看,就要打开10个地址,而微服务系统可远不止10个那么少,所以我们要用一个统一地址,可以选择服务进行自由切换。配置如下:

  我们已经建立了一个服务,并且配置好了swagger,我们在新建一个一样的服务,并且一样配置好swagger,并且写2个接口

  再新建一个服务,做为swagger统一入口服务,一样引入nuget包,DI注入也是一样的,只需要在添加中间件的时候利用swagger的SwaggerUIOptions的扩展SwaggerEndpoint,就可以集中配置,如代码

 var apis = new List<string>();
            apis.Add("http://localhost:5001");
            apis.Add("http://localhost:5002");
           
            app.UseSwagger()
            .UseSwaggerUI(c =>
            {
                apis.ForEach(m =>
                {
                    c.SwaggerEndpoint($"{m}/swagger/v1/swagger.json", m);
                });
            });

然后,三个服务同时启动,打开这个统一文档服务的swagger地址如下图:

846824-20220923155511749-1833987814.png

看右上角,可以切换服务定义了,这回方便了。回到统一服务的,中间件配置的代码上,因为人家是endpoint,是地址,所以我们只能如此简陋的配置,在切换地方显示的是地址,真实项目中,这样肯定不行的,首先开发人员要知道所有服务地址是不显示的,其次通过地址切换,你也不知道服务是干啥的,所以实际项目中,我们是利用网关+consul+配置中心的地址规则,来集中配置。如下图

846824-20220923160134007-1152156529.png

最后的统一文档服务的目标切换,就是服务名称

846824-20220923160333445-2005465955.png

全文结束。。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK