当前位置:网站首页>go iris框架实现多服务Demo:通过(监听8083端口的)服务1中的接口启动(监听8084端口的)服务2
go iris框架实现多服务Demo:通过(监听8083端口的)服务1中的接口启动(监听8084端口的)服务2
2022-04-23 06:15:00 【玩哈哈527】
go iris框架实现多服务Demo:通过(监听8083端口的)服务1中的接口启动(监听8084端口的)服务2
前言
常见情况下,在一个应用程序中会监听不同端口的多个服务,比如:服务1实现其相应接口功能,服务2实现其相应接口功能。 此demo示例,目的是:通过在服务1中的某个接口来启动服务2。一、DEMO示例
1.引入库
代码如下(示例):
package main
import (
"context"
"fmt"
"log"
"time"
"github.com/kataras/iris/v12"
"golang.org/x/sync/errgroup"
)
var g errgroup.Group
var sig string
var app2 *iris.Application
func main() {
sig = "start"
g.Go(startApp1)
if err := g.Wait(); err != nil {
fmt.Println(fmt.Sprintf("startup service failed, err:%v\n", err))
}
}
func startApp1() error {
app := iris.New()
app.Handle("GET", "/hello1", hello1)
app.Handle("GET", "/restart", restart)
log.Println("http://localhost:8083/hello1")
log.Println("http://localhost:8084/hello2")
log.Println("http://localhost:8083/restart")
err := app.Listen(":8083")
return err
}
func startApp2() error {
var err error
app2 = iris.New()
app2.Handle("GET", "/hello2", hello2)
err = app2.Listen(":8084")
return err
}
func restart(c iris.Context) {
if sig == "start" {
g.Go(startApp2)
fmt.Println("已启动http://localhost:8084")
sig = "restart"
} else if sig == "restart" {
//关闭监听
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
if err := app2.Shutdown(ctx); nil != err {
log.Fatalf("server shutdown failed, err: %v\n", err)
}
log.Println("server gracefully shutdown")
fmt.Println("已停止http://localhost:8084")
//启动监听
g.Go(startApp2)
//app2.Listen(":8084")
fmt.Println("已启动http://localhost:8084")
sig = "restart"
}
c.WriteString("已重启")
}
func hello1(c iris.Context) {
c.WriteString("hello app1")
}
func hello2(c iris.Context) {
c.WriteString("hello app2")
}
总结
完成的功能流程:1.启动程序,服务1 监听端口http://localhost:8083,包含接口:http://localhost:8083/hello1 和 http://localhost:8083/restart
2.通过http://localhost:8083/restart接口启动服务2
3.服务2启动后,其接口http://localhost:8084/hello2正常使用
版权声明
本文为[玩哈哈527]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qq_28058509/article/details/122713278
边栏推荐
猜你喜欢
随机推荐
Unable to determine the device handle for GPU 0000:02:00.0: GPU is lost.
“泉”力以赴·同“州”共济|北峰人一直在行动
PyTorch 19. PyTorch中相似操作的区别与联系
Modifying a column with the 'identity' pattern is not supported
PyTorch 9. 优化器
PyTorch 10. 学习率
unhandled system error, NCCL version 2.7.8
Draw margin curve in arcface
PyTorch 11.正则化
GIS实战应用案例100篇(五十二)-ArcGIS中用栅格裁剪栅格,如何保持行列数量一致并且对齐?
社区版阿里MQ普通消息发送订阅Demo
[8] Assertion failed: dims.nbDims == 4 || dims.nbDims == 5
基于51单片机的三路超声波测距系统(定时器方式测距)
主流 RTOS 评估
Use originpro express for free
PyTorch 20. PyTorch技巧(持续更新)
机器学习——模型优化
美摄科技推出桌面端专业视频编辑解决方案——美映PC版
城市应急管理|城市突发事故应急通信指挥调度系统
机器视觉系列(01)---综述