• 8_多服务运行.md


    运行多个服务

    gin可以在多个端口启动服务,例如:

    package main
    
    import (
    	"log"
    	"net/http"
    	"time"
    
    	"github.com/gin-gonic/gin"
    	"golang.org/x/sync/errgroup"
    )
    
    var (
    	g errgroup.Group
    )
    
    func router01() http.Handler {
    	e := gin.New()
    	e.Use(gin.Recovery())
    	e.GET("/", func(c *gin.Context) {
    		c.JSON(
    			http.StatusOK,
    			gin.H{
    				"code":  http.StatusOK,
    				"error": "Welcome server 01",
    			},
    		)
    	})
    
    	return e
    }
    
    func router02() http.Handler {
    	e := gin.New()
    	e.Use(gin.Recovery())
    	e.GET("/", func(c *gin.Context) {
    		c.JSON(
    			http.StatusOK,
    			gin.H{
    				"code":  http.StatusOK,
    				"error": "Welcome server 02",
    			},
    		)
    	})
    
    	return e
    }
    
    func main() {
    	server01 := &http.Server{
    		Addr:         ":8080",
    		Handler:      router01(),
    		ReadTimeout:  5 * time.Second,
    		WriteTimeout: 10 * time.Second,
    	}
    
    	server02 := &http.Server{
    		Addr:         ":8081",
    		Handler:      router02(),
    		ReadTimeout:  5 * time.Second,
    		WriteTimeout: 10 * time.Second,
    	}
       // 借助errgroup.Group或者自行开启两个goroutine分别启动两个服务
    	g.Go(func() error {
    		return server01.ListenAndServe()
    	})
    
    	g.Go(func() error {
    		return server02.ListenAndServe()
    	})
    
    	if err := g.Wait(); err != nil {
    		log.Fatal(err)
    	}
    }
    
  • 相关阅读:
    sb世博
    seo 工具集锦
    各种Windows 操作系统中的 .NET Framework 支持
    httplib2模拟登陆
    python tips
    B2C电子商务能否通吃线上线下?
    复制镜像
    Scale Stack vs node.js vs Twisted vs Eventlet
    pool=eventlet.GreenPool(20)
    nginx最新部署
  • 原文地址:https://www.cnblogs.com/nsfoxer/p/14491864.html
Copyright © 2020-2023  润新知