Go项目快速集成Swagger UI

swag

Swag将Go的注释转换为Swagger2.0文档。我们为流行的 Go Web Framework 创建了各种插件,这样可以与现有Go项目快速集成(使用Swagger UI)。

目录

  • 快速开始
  • 支持的Web框架
  • 如何与Gin集成
  • 格式化说明
  • 开发现状
  • 声明式注释格式
    • 通用API信息
    • API操作
    • 安全性
  • 样例
    • 多行的描述
    • 用户自定义的具有数组类型的结构
    • 响应对象中的模型组合
    • 在响应中增加头字段
    • 使用多路径参数
    • 结构体的示例值
    • 结构体描述
    • 使用swaggertype标签更改字段类型
    • 使用swaggerignore标签排除字段
    • 将扩展信息添加到结构字段
    • 对展示的模型重命名
    • 如何使用安全性注释
  • 项目相关

快速开始

  1. 将注释添加到API源代码中,请参阅声明性注释格式。
  2. 使用如下命令下载swag:
go install github.com/swaggo/swag/cmd/swag@latest

从源码开始构建的话,需要有Go环境(1.18及以上版本)。

或者从github的release页面下载预编译好的二进制文件。

  1. 在包含main.go文件的项目根目录运行swag init。这将会解析注释并生成需要的文件(docs文件夹和docs/docs.go)。
swag init

确保导入了生成的docs/docs.go文件,这样特定的配置文件才会被初始化。如果通用API注释没有写在main.go中,可以使用-g标识符来告知swag。

swag init -g http/api.go
  1. (可选) 使用fmt格式化 SWAG 注释。(请先升级到最新版本)
swag fmt

swag cli

swag init -h
NAME:
   swag init - Create docs.go

USAGE:
   swag init [command options] [arguments...]

OPTIONS:
   --generalInfo value, -g value          API通用信息所在的go源文件路径,如果是相对路径则基于API解析目录 (默认: "main.go")
   --dir value, -d value                  API解析目录 (默认: "./")
   --exclude value                        解析扫描时排除的目录,多个目录可用逗号分隔(默认:空)
   --propertyStrategy value, -p value     结构体字段命名规则,三种:snakecase,camelcase,pascalcase (默认: "camelcase")
   --output value, -o value               文件(swagger.json, swagger.yaml and doc.go)输出目录 (默认: "./docs")
   --parseVendor                          是否解析vendor目录里的go源文件,默认不
   --parseDependency                      是否解析依赖目录中的go源文件,默认不
   --markdownFiles value, --md value      指定API的描述信息所使用的markdown文件所在的目录
   --generatedTime                        是否输出时间到输出文件docs.go的顶部,默认是
   --codeExampleFiles value, --cef value  解析包含用于 x-codeSamples 扩展的代码示例文件的文件夹,默认禁用
   --parseInternal                        解析 internal 包中的go文件,默认禁用
   --parseDepth value                     依赖解析深度 (默认: 100)
   --instanceName value                   设置文档实例名 (默认: "swagger")
swag fmt -h
NAME:
   swag fmt - format swag comments

USAGE:
   swag fmt [command options] [arguments...]

OPTIONS:
   --dir value, -d value          API解析目录 (默认: "./")
   --exclude value                解析扫描时排除的目录,多个目录可用逗号分隔(默认:空)
   --generalInfo value, -g value  API通用信息所在的go源文件路径,如果是相对路径则基于API解析目录 (默认: "main.go")
   --help, -h                     show help (default: false)

支持的Web框架

  • gin
  • echo
  • buffalo
  • net/http
  • gorilla/mux
  • go-chi/chi
  • flamingo
  • fiber
  • atreugo
  • hertz

如何与Gin集成

点击此处查看示例源代码。

  1. 使用swag init生成Swagger2.0文档后,导入如下代码包:
import "github.com/swaggo/gin-swagger" // gin-swagger middleware
import "github.com/swaggo/files" // swagger embed files
  1. main.go源代码中添加通用的API注释:
// @title           Swagger Example API
// @version         1.0
// @description     This is a sample server celler server.
// @termsOfService  http://swagger.io/terms/

// @contact.name   API Support
// @contact.url    http://www.swagger.io/support
// @contact.email  support@swagger.io

// @license.name  Apache 2.0
// @license.url   http://www.apache.org/licenses/LICENSE-2.0.html

// @host      localhost:8080
// @BasePath  /api/v1

// @securityDefinitions.basic  BasicAuth

// @externalDocs.description  OpenAPI
// @externalDocs.url          https://swagger.io/resources/open-api/
func main() {
    r := gin.Default()

    c := controller.NewController()

    v1 := r.Group("/api/v1")
    {
        accounts := v1.Group("/accounts")
        {
            accounts.GET(":id", c.ShowAccount)
            accounts.GET("", c.ListAccounts)
            accounts.POST("", c.AddAccount)
            accounts.DELETE(":id", c.DeleteAccount)
            accounts.PATCH(":id", c.UpdateAccount)
            accounts.POST(":id/images", c.UploadAccountImage)
        }
    //...
    }
    r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
    r.Run(":8080")
}
//...

此外,可以动态设置一些通用的API信息。生成的代码包docs导出SwaggerInfo变量,使用该变量可以通过编码的方式设置标题、描述、版本、主机和基础路径。使用Gin的示例:

package main

import (
    "github.com/gin-gonic/gin"
    "github.com/swaggo/files"
    "github.com/swaggo/gin-swagger"

    "./docs" // docs is generated by Swag CLI, you have to import it.
)

// @contact.name   API Support
// @contact.url    http://www.swagger.io/support
// @contact.email  support@swagger.io

// @license.name  Apache 2.0
// @license.url   http://www.apache.org/licenses/LICENSE-2.0.html
func main() {

    // programatically set swagger info
    docs.SwaggerInfo.Title = "Swagger Example API"
    docs.SwaggerInfo.Description = "This is a sample server Petstore server."
    docs.SwaggerInfo.Version = "1.0"
    docs.SwaggerInfo.Host = "petstore.swagger.io"
    docs.SwaggerInfo.BasePath = "/v2"
    docs.SwaggerInfo.Schemes = []string{"http", "https"}

    r := gin.New()

    // use ginSwagger middleware to serve the API docs
    r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))

    r.Run()
}
  1. controller代码中添加API操作注释:
package controller

import (
    "fmt"
    "net/http"
    "strconv"

    "github.com/gin-gonic/gin"
    "github.com/swaggo/swag/example/celler/httputil"
    "github.com/swaggo/swag/example/celler/model"
)

// ShowAccount godoc
// @Summary      Show an account
// @Description  get string by ID
// @Tags         accounts
// @Accept       json
// @Produce      json
// @Param        id   path      int  true  "Account ID"
// @Success      200  {object}  model.Account
// @Failure      400  {object}  httputil.HTTPError
// @Failure      404  {object}  httputil.HTTPError
// @Failure      500  {object}  httputil.HTTPError
// @Router       /accounts/{id} [get]
func (c *Controller) ShowAccount(ctx *gin.Context) {
  id := ctx.Param("id")
  aid, err := strconv.Atoi(id)
  if err != nil {
    httputil.NewError(ctx, http.StatusBadRequest, err)
    return
  }
  account, err := model.AccountOne(aid)
  if err != nil {
    httputil.NewError(ctx, http.StatusNotFound, err)
    return
  }
  ctx.JSON(http.StatusOK, account)
}

// ListAccounts godoc
// @Summary      List accounts
// @Description  get accounts
// @Tags         accounts
// @Accept       json
// @Produce      json
// @Param        q    query     string  false  "name search by q"  Format(email)
// @Success      200  {array}   model.Account
// @Failure      400  {object}  httputil.HTTPError
// @Failure      404  {object}  httputil.HTTPError
// @Failure      500  {object}  httputil.HTTPError
// @Router       /accounts [get]
func (c *Controller) ListAccounts(ctx *gin.Context) {
  q := ctx.Request.URL.Query().Get("q")
  accounts, err := model.AccountsAll(q)
  if err != nil {
    httputil.NewError(ctx, http.StatusNotFound, err)
    return
  }
  ctx.JSON(http.StatusOK, accounts)
}
//...
swag init
  1. 运行程序,然后在浏览器中访问 http://localhost:8080/swagger/index.html 。将看到Swagger 2.0 Api文档,如下所示:

swagger_index.html

格式化说明

可以针对Swag的注释自动格式化,就像go fmt
此处查看格式化结果 here.

示例:

swag fmt

排除目录(不扫描)示例:

swag fmt -d ./ --exclude ./internal

开发现状

Swagger 2.0 文档

  • Basic Structure
  • API Host and Base Path
  • Paths and Operations
  • Describing Parameters
  • Describing Request Body
  • Describing Responses
  • MIME Types
  • Authentication
    • Basic Authentication
    • API Keys
  • Adding Examples
  • File Upload
  • Enums
  • Grouping Operations With Tags
  • Swagger Extensions

声明式注释格式

通用API信息

示例 celler/main.go

注释说明示例
title必填 应用程序的名称。// @title Swagger Example API
version必填 提供应用程序API的版本。// @version 1.0
description应用程序的简短描述。// @description This is a sample server celler server.
tag.name标签的名称。// @tag.name This is the name of the tag
tag.description标签的描述。// @tag.description Cool Description
tag.docs.url标签的外部文档的URL。// @tag.docs.url https://example.com
tag.docs.description标签的外部文档说明。// @tag.docs.description Best example documentation
termsOfServiceAPI的服务条款。// @termsOfService http://swagger.io/terms/
contact.name公开的API的联系信息。// @contact.name API Support
contact.url联系信息的URL。 必须采用网址格式。// @contact.url http://www.swagger.io/support
contact.email联系人/组织的电子邮件地址。 必须采用电子邮件地址的格式。// @contact.email support@swagger.io
license.name必填 用于API的许可证名称。// @license.name Apache 2.0
license.url用于API的许可证的URL。 必须采用网址格式。// @license.url http://www.apache.org/licenses/LICENSE-2.0.html
host运行API的主机(主机名或IP地址)。// @host localhost:8080
BasePath运行API的基本路径。// @BasePath /api/v1
acceptAPI 可以使用的 MIME 类型列表。 请注意,Accept 仅影响具有请求正文的操作,例如 POST、PUT 和 PATCH。 值必须如“Mime类型”中所述。// @accept json
produceAPI可以生成的MIME类型的列表。值必须如“Mime类型”中所述。// @produce json
query.collection.format请求URI query里数组参数的默认格式:csv,multi,pipes,tsv,ssv。 如果未设置,则默认为csv。// @query.collection.format multi
schemes用空格分隔的请求的传输协议。// @schemes http https
externalDocs.descriptionDescription of the external document.// @externalDocs.description OpenAPI
externalDocs.urlURL of the external document.// @externalDocs.url https://swagger.io/resources/open-api/
x-name扩展的键必须以x-开头,并且只能使用json值// @x-example-key {“key”: “value”}

使用Markdown描述

如果文档中的短字符串不足以完整表达,或者需要展示图片,代码示例等类似的内容,则可能需要使用Markdown描述。要使用Markdown描述,请使用一下注释。

注释说明示例
title必填 应用程序的名称。// @title Swagger Example API
version必填 提供应用程序API的版本。// @version 1.0
description.markdown应用程序的简短描述。 从api.md文件中解析。 这是@description的替代用法。// @description.markdown No value needed, this parses the description from api.md
tag.name标签的名称。// @tag.name This is the name of the tag
tag.description.markdown标签说明,这是tag.description的替代用法。 该描述将从名为tagname.md的文件中读取。// @tag.description.markdown

API操作

Example celler/controller

注释描述
description操作行为的详细说明。
description.markdown应用程序的简短描述。该描述将从名为endpointname.md的文件中读取。
id用于标识操作的唯一字符串。在所有API操作中必须唯一。
tags每个API操作的标签列表,以逗号分隔。
summary该操作的简短摘要。
acceptAPI 可以使用的 MIME 类型列表。 请注意,Accept 仅影响具有请求正文的操作,例如 POST、PUT 和 PATCH。 值必须如“Mime类型”中所述。
produceAPI可以生成的MIME类型的列表。值必须如“Mime类型”中所述。
param用空格分隔的参数。param name,param type,data type,is mandatory?,comment attribute(optional)
security每个API操作的安全性。
success以空格分隔的成功响应。return code,{param type},data type,comment
failure以空格分隔的故障响应。return code,{param type},data type,comment
response与success、failure作用相同
header以空格分隔的头字段。 return code,{param type},data type,comment
router以空格分隔的路径定义。 path,[httpMethod]
x-name扩展字段必须以x-开头,并且只能使用json值。

Mime类型

swag 接受所有格式正确的MIME类型, 即使匹配 */*。除此之外,swag还接受某些MIME类型的别名,如下所示:

AliasMIME Type
jsonapplication/json
xmltext/xml
plaintext/plain
htmltext/html
mpfdmultipart/form-data
x-www-form-urlencodedapplication/x-www-form-urlencoded
json-apiapplication/vnd.api+json
json-streamapplication/x-json-stream
octet-streamapplication/octet-stream
pngimage/png
jpegimage/jpeg
gifimage/gif

参数类型

  • query
  • path
  • header
  • body
  • formData

数据类型

  • string (string)
  • integer (int, uint, uint32, uint64)
  • number (float32)
  • boolean (bool)
  • user defined struct

安全性

注释描述参数示例
securitydefinitions.basicBasic auth.// @securityDefinitions.basic BasicAuth
securitydefinitions.apikeyAPI key auth.in, name// @securityDefinitions.apikey ApiKeyAuth
securitydefinitions.oauth2.applicationOAuth2 application auth.tokenUrl, scope// @securitydefinitions.oauth2.application OAuth2Application
securitydefinitions.oauth2.implicitOAuth2 implicit auth.authorizationUrl, scope// @securitydefinitions.oauth2.implicit OAuth2Implicit
securitydefinitions.oauth2.passwordOAuth2 password auth.tokenUrl, scope// @securitydefinitions.oauth2.password OAuth2Password
securitydefinitions.oauth2.accessCodeOAuth2 access code auth.tokenUrl, authorizationUrl, scope// @securitydefinitions.oauth2.accessCode OAuth2AccessCode
参数注释示例
in// @in header
name// @name Authorization
tokenUrl// @tokenUrl https://example.com/oauth/token
authorizationurl// @authorizationurl https://example.com/oauth/authorize
scope.hoge// @scope.write Grants write access

属性

// @Param   enumstring  query     string     false  "string enums"       Enums(A, B, C)
// @Param   enumint     query     int        false  "int enums"          Enums(1, 2, 3)
// @Param   enumnumber  query     number     false  "int enums"          Enums(1.1, 1.2, 1.3)
// @Param   string      query     string     false  "string valid"       minlength(5)  maxlength(10)
// @Param   int         query     int        false  "int valid"          minimum(1)    maximum(10)
// @Param   default     query     string     false  "string default"     default(A)
// @Param   collection  query     []string   false  "string collection"  collectionFormat(multi)
// @Param   extensions  query     []string   false  "string collection"  extensions(x-example=test,x-nullable)

也适用于结构体字段:

type Foo struct {
    Bar string `minLength:"4" maxLength:"16"`
    Baz int `minimum:"10" maximum:"20" default:"15"`
    Qux []string `enums:"foo,bar,baz"`
}

当前可用的

字段名类型描述
default*声明如果未提供任何参数,则服务器将使用的默认参数值,例如,如果请求中的客户端未提供该参数,则用于控制每页结果数的“计数”可能默认为100。 (注意:“default”对于必需的参数没有意义)。参看 https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-6.2。 与JSON模式不同,此值务必符合此参数的定义类型。
maximumnumber参看 https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.2.
minimumnumber参看 https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.3.
maxLengthinteger参看 https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.1.
minLengthinteger参看 https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.2.
enums[*]参看 https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.5.1.
formatstring上面提到的类型的扩展格式。有关更多详细信息,请参见数据类型格式。
collectionFormatstring指定query数组参数的格式。 可能的值为:
  • csv - 逗号分隔值 foo,bar.
  • ssv - 空格分隔值 foo bar.
  • tsv - 制表符分隔值 foo\tbar.
  • pipes - 管道符分隔值 foo|bar.
  • multi - 对应于多个参数实例,而不是单个实例 foo=bar&foo=baz 的多个值。这仅对“query”或“formData”中的参数有效。
默认值是 csv

进一步的

字段名类型描述
multipleOfnumberSee https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.1.
patternstringSee https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.3.
maxItemsintegerSee https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.2.
minItemsintegerSee https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.3.
uniqueItemsbooleanSee https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.4.

样例

多行的描述

可以在常规api描述或路由定义中添加跨越多行的描述,如下所示:

// @description This is the first line
// @description This is the second line
// @description And so forth.

用户自定义的具有数组类型的结构

// @Success 200 {array} model.Account <-- This is a user defined struct.
package model

type Account struct {
    ID   int    `json:"id" example:"1"`
    Name string `json:"name" example:"account name"`
}

响应对象中的模型组合

// JSONResult的data字段类型将被proto.Order类型替换
@success 200 {object} jsonresult.JSONResult{data=proto.Order} "desc"
type JSONResult struct {
    Code    int          `json:"code" `
    Message string       `json:"message"`
    Data    interface{}  `json:"data"`
}

type Order struct { //in `proto` package
    ...
}
  • 还支持对象数组和原始类型作为嵌套响应
@success 200 {object} jsonresult.JSONResult{data=[]proto.Order} "desc"
@success 200 {object} jsonresult.JSONResult{data=string} "desc"
@success 200 {object} jsonresult.JSONResult{data=[]string} "desc"
  • 替换多个字段的类型。如果某字段不存在,将添加该字段。
@success 200 {object} jsonresult.JSONResult{data1=string,data2=[]string,data3=proto.Order,data4=[]proto.Order} "desc"

在响应中增加头字段

// @Success      200              {string}  string    "ok"
// @failure      400              {string}  string    "error"
// @response     default          {string}  string    "other error"
// @Header       200              {string}  Location  "/entity/1"
// @Header       200,400,default  {string}  Token     "token"
// @Header       all              {string}  Token2    "token2"

使用多路径参数

/// ...
// @Param  group_id    path  int  true  "Group ID"
// @Param  account_id  path  int  true  "Account ID"
// ...
// @Router /examples/groups/{group_id}/accounts/{account_id} [get]

结构体的示例值

type Account struct {
    ID   int    `json:"id" example:"1"`
    Name string `json:"name" example:"account name"`
    PhotoUrls []string `json:"photo_urls" example:"http://test/image/1.jpg,http://test/image/2.jpg"`
}

结构体描述

type Account struct {
    // ID this is userid
    ID   int    `json:"id"`
    Name string `json:"name"` // This is Name
}

使用swaggertype标签更改字段类型

#201

type TimestampTime struct {
    time.Time
}

///实现encoding.JSON.Marshaler接口
func (t *TimestampTime) MarshalJSON() ([]byte, error) {
    bin := make([]byte, 16)
    bin = strconv.AppendInt(bin[:0], t.Time.Unix(), 10)
    return bin, nil
}

///实现encoding.JSON.Unmarshaler接口
func (t *TimestampTime) UnmarshalJSON(bin []byte) error {
    v, err := strconv.ParseInt(string(bin), 10, 64)
    if err != nil {
        return err
    }
    t.Time = time.Unix(v, 0)
    return nil
}
///

type Account struct {
    // 使用`swaggertype`标签将别名类型更改为内置类型integer
    ID     sql.NullInt64 `json:"id" swaggertype:"integer"`

    // 使用`swaggertype`标签更改struct类型为内置类型integer
    RegisterTime TimestampTime `json:"register_time" swaggertype:"primitive,integer"`

    // Array types can be overridden using "array,<prim_type>" format
    Coeffs []big.Float `json:"coeffs" swaggertype:"array,number"`
}

#379

type CerticateKeyPair struct {
    Crt []byte `json:"crt" swaggertype:"string" format:"base64" example:"U3dhZ2dlciByb2Nrcw=="`
    Key []byte `json:"key" swaggertype:"string" format:"base64" example:"U3dhZ2dlciByb2Nrcw=="`
}

生成的swagger文档如下:

"api.MyBinding": {
  "type":"object",
  "properties":{
    "crt":{
      "type":"string",
      "format":"base64",
      "example":"U3dhZ2dlciByb2Nrcw=="
    },
    "key":{
      "type":"string",
      "format":"base64",
      "example":"U3dhZ2dlciByb2Nrcw=="
    }
  }
}

使用swaggerignore标签排除字段

type Account struct {
    ID   string    `json:"id"`
    Name string     `json:"name"`
    Ignored int     `swaggerignore:"true"`
}

将扩展信息添加到结构字段

type Account struct {
    ID   string    `json:"id"   extensions:"x-nullable,x-abc=def,!x-omitempty"` // 扩展字段必须以"x-"开头
}

生成swagger文档,如下所示:

"Account": {
    "type": "object",
    "properties": {
        "id": {
            "type": "string",
            "x-nullable": true,
            "x-abc": "def",
            "x-omitempty": false
        }
    }
}

对展示的模型重命名

type Resp struct {
    Code int
}//@name Response

如何使用安全性注释

通用API信息。

// @securityDefinitions.basic BasicAuth

// @securitydefinitions.oauth2.application OAuth2Application
// @tokenUrl https://example.com/oauth/token
// @scope.write Grants write access
// @scope.admin Grants read and write access to administrative information

每个API操作。

// @Security ApiKeyAuth

使用AND条件。

// @Security ApiKeyAuth
// @Security OAuth2Application[write, admin]

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

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

相关文章

【每日一题】【12.20】2828.判别首字母缩略词

&#x1f525;博客主页&#xff1a; A_SHOWY&#x1f3a5;系列专栏&#xff1a;力扣刷题总结录 数据结构 云计算 数字图像处理 力扣每日一题_ 1.题目链接 2828. 判别首字母缩略词https://leetcode.cn/problems/check-if-a-string-is-an-acronym-of-words/ 2.题目描述 今天…

RTDETR论文快速理解和代码快速实现(训练与预测)

文章目录 前言一、摘要二、论文目的三、论文贡献四、模型结构1、模型整体结构2、backbone结构3、neck结构4、混合编码器(neck) 五、RTDERT模型训练(data-->train)1、环境安装2、训练1、数据准备2、数据yaml文件3、训练代码4、训练运行结果 3、推理1、推理代码2、推理运行结果…

Nginx快速入门:安装目录结构详解及核心配置解读(二)

0. 引言 上节我们讲解了nginx的应用场景和安装&#xff0c;本节继续针对nginx的各个目录文件进行讲解&#xff0c;让大家更加深入的认识nginx。并通过一个实操案例&#xff0c;带大家来实际认知nginx的核心配置 1. nginx安装目录结构 首先nginx的默认安装目录为&#xff1a;…

原子学习笔记3——使用tslib库

一、tslib介绍 tslib 是专门为触摸屏设备所开发的 Linux 应用层函数库&#xff0c;并且是开源。 tslib 为触摸屏驱动和应用层之间的适配层&#xff0c;它把应用程序中读取触摸屏 struct input_event 类型数据&#xff08;这是输入设备上报给应用层的原始数据&#xff09;并进行…

Elasticsearch常见面试题

文章目录 1.简单介绍下ES&#xff1f;2.简单介绍当前可以下载的ES稳定版本&#xff1f;3.安装ES前需要安装哪种软件&#xff1f;4.请介绍启动ES服务的步骤&#xff1f;5.ES中的倒排索引是什么&#xff1f;6. ES是如何实现master选举的&#xff1f;7. 如何解决ES集群的脑裂问题8…

SpringBoot-XXLJOB提供动态API调度任务

目录 一、项目版本 二、XXL-JOB提供动态API controller层 service层 三、SpringBoot项目 pom model XxlJobUtil-工具类 XXL-JOB是一个分布式任务调度平台&#xff0c;其核心设计目标是开发迅速、学习简单、轻量级、易扩展。现已开放源代码并接入多家公司线上产品线&…

Gateway网关-网关的cors跨域配置

目录 一、跨域 二、解决方案 三、实际测试 3.1 html调用接口 3.2 跨域问题复现 3.3 application文件中配置CORS 3.4 问题解决 一、跨域 跨域问题&#xff1a;浏览器禁止请求的发起者与服务端发生跨域ajax请求&#xff0c;请求被浏览器拦截的问题 跨域&#xff1a;…

第四节TypeScript 声明变量

1、typescript变量声明 变量是一种使用方便的占位符&#xff0c;用于引用计算机内存地址。 我们可以把变量看做存储数据的容器。 typescript变量的命名规则&#xff1a; 变量名称可以包含数字和字母。除了下划线_和美元$符号外&#xff0c;不能包含其它特殊字符&#xff0c…

基于Alpha-Beta剪枝树的井字棋人机博弈系统的实现

这篇文章讨论了算法的基本概念与特性&#xff0c;并介绍了五种常见的算法类型&#xff1a;分治法、动态规划、贪心算法、回溯法和分支限界法。文章以井字棋博弈中的Alpha-Beta剪枝树作为示例&#xff0c;详细解释了该算法的应用和原理。Alpha-Beta剪枝树是一种用于实现游戏AI的…

Python数据加密:保障信息安全的最佳实践

更多资料获取 &#x1f4da; 个人网站&#xff1a;ipengtao.com 随着信息技术的发展&#xff0c;数据安全成为越来越重要的议题。在Python中&#xff0c;有多种方法可以用于数据加密&#xff0c;以确保敏感信息在传输和存储过程中不被泄露或篡改。本文将详细介绍Python中数据加…

智能优化算法应用:基于梯度算法3D无线传感器网络(WSN)覆盖优化 - 附代码

智能优化算法应用&#xff1a;基于梯度算法3D无线传感器网络(WSN)覆盖优化 - 附代码 文章目录 智能优化算法应用&#xff1a;基于梯度算法3D无线传感器网络(WSN)覆盖优化 - 附代码1.无线传感网络节点模型2.覆盖数学模型及分析3.梯度算法4.实验参数设定5.算法结果6.参考文献7.MA…

服务器数据恢复-EMC存储raid5磁盘物理故障离线的数据恢复案例

服务器数据恢复环境&故障&#xff1a; 一台emc某型号存储服务器&#xff0c;存储服务器上组建了一组raid5磁盘阵列&#xff0c;阵列中有两块磁盘作为热备盘使用。存储服务器在运行过程中有两块磁盘出现故障离线&#xff0c;但是只有一块热备盘激活&#xff0c;最终导致该ra…

文件操作入门指南

目录 一、为什么使用文件 二、什么是文件 2.1 程序文件 2.2 数据文件 2.3 文件名 三、文件的打开和关闭 3.1 文件指针 3.2 文件的打开和关闭 四、文件的顺序读写 ​编辑 &#x1f33b;深入理解 “流”&#xff1a; &#x1f342;文件的顺序读写函数介绍&#xff1a; …

系列十四(面试)、谈谈你对StackOverflowError的理解?

一、StackOverflowError 1.1、概述 StackOverflowError是栈内存溢出的意思。栈中主要存储的是8种基本数据类型 引用类型 实例方法&#xff0c;栈的空间也是有限的&#xff0c;当存储进栈中的容量大于栈的最大容量时&#xff0c;就会报StackOverflowError的错误。 1.2、案例 …

如何入门 GPT 并快速跟上当前的大语言模型 LLM 进展?

入门GPT 首先说第一个问题&#xff1a;如何入门GPT模型&#xff1f; 最直接的方式当然是去阅读官方的论文。GPT模型从2018年的GPT-1到现在的GPT-4已经迭代了好几个版本&#xff0c;通过官方团队发表的论文是最能准确理清其发展脉络的途径&#xff0c;其中包括GPT模型本身和一…

最详细手把手教你安装 Vivado2017.4

软件下载 官网可下载各个版本 百度网盘链接 Vivado2017.4 License 软件安装 解压缩安装包&#xff0c;双击运行安装程序 xsetup.exe&#xff1a; 忽略软件更新&#xff0c;点击 Continue&#xff1a; 点击 Next&#xff1a; 全部勾选 I Agree&#xff0c;点击 Next&#x…

从0到1打造一款WebStyle串口调试工具

Tip&#xff1a;No Ego Some programmers have a huge problem: their own ego. But there is no time for developing an ego. There is no time for being a rockstar. Who is it who decides about your quality as programmer? You? No. The others? Probably. But can …

Python (十二) NumPy操作

程序员的公众号&#xff1a;源1024&#xff0c;获取更多资料&#xff0c;无加密无套路&#xff01; 最近整理了一波电子书籍资料&#xff0c;包含《Effective Java中文版 第2版》《深入JAVA虚拟机》&#xff0c;《重构改善既有代码设计》&#xff0c;《MySQL高性能-第3版》&…

程序员的20大Git面试问题及答案

文章目录 1.什么是Git&#xff1f;2.Git 工作流程3.在 Git 中提交的命令是什么&#xff1f;4.什么是 Git 中的“裸存储库”&#xff1f;5.Git 是用什么语言编写的&#xff1f;6.在Git中&#xff0c;你如何还原已经 push 并公开的提交&#xff1f;7.git pull 和 git fetch 有什么…

计算机网络(3):数据链路层

数据链路层属于计算机网络的低层。 数据链路层使用的信道主要有以下两种类型&#xff1a; (1)点对点信道。这种信道使用一对一的点对点通信方式。 (2)广播信道。这种信道使用一对多的广播通信方式。广播信道上连接的主机很多&#xff0c;因此必须使用专用的共享信道协议来协调这…
最新文章