• 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)
    	}
    }
    
  • 相关阅读:
    elemenui数据表格加入计数器和输入框
    递归求阶乘
    递归累和
    递归
    file类
    Object类
    首页背景图
    异常的处理
    数据结构有什么用?常见的数据结构有什么?
    线程、并发、并行、进程是什么,以及如何开启新的线程?
  • 原文地址:https://www.cnblogs.com/nsfoxer/p/14491864.html
Copyright © 2020-2023  润新知