GO微服务实战 – 01搭建微服务端与web端

微服务框架

浏览器访问微服务.png

  • 可以在服务发现中搭建集群,引入多个同名服务
  • 在浏览器和web服务之间引入nginx,做反向代理

项目准备

  1. 准备项目环境

    1. 创建项目目录 web、service
    2. 在 web 端 使用 MVC
    3. 创建项目常用目录: conf 配置文件、utils 工具类、bin可执行文件、test测试目录
    4. util包中导入异常处理文件error.go
    5. 导入前端资源 html/ 到 view/ 中
  2. 开发项目

    1. 开发 微服务端
    2. 开发 web 服务(客户端)

项目

1. 获取session信息服务

router.GET("/api/v1.0/session", controller.GetSession) //注册路由
复制代码
func GetSession(ctx *gin.Context) {
	resp := make(map[string]string)
	resp["errno"] = utils.RECODE_SESSIONERR
	resp["errmsg"] = utils.RecodeText(utils.RECODE_SESSIONERR)
	ctx.JSON(http.StatusOK, resp) //json序列化
}
复制代码

2. 获取验证码图片服务

– Web端实现

  • 去 github 中搜索 “captcha” 关键词。 过滤 Go语言。 —— afocus/captcha

  • 使用 go get github.com/afocus/captcha 下载源码包。

  • 参照 github 中的示例代码,测试生成 图片验证码

router.GET("/api/v1.0/imagecode/:uuid", controller.GetImageCd)
复制代码
func GetImageCd(ctx *gin.Context) {
	// 获取uuid
	uuid := ctx.Param("uuid")
	fmt.Println(uuid)
	// 生成验证码
	cap := captcha.New() // 初始化对象
	cap.SetFont("/Users/yaxuan/go/src/bj38web/web/conf/comic.ttf") // 设置字体
	cap.SetSize(128, 64) // 设置验证码大小
	cap.SetDisturbance(captcha.MEDIUM) // 设置干扰强度
	cap.SetFrontColor(color.RGBA{0,0,0, 255}) // 设置前景色
	cap.SetBkgColor(color.RGBA{100,0,255, 255}, color.RGBA{255,0,127, 255}, color.RGBA{255,255,10, 255}) // 设置背景色
	img,str := cap.Create(4,captcha.NUM) // 生成字体
	png.Encode(ctx.Writer, img)
	fmt.Println(str)
}
复制代码

– 将图片验证码功能移植微服务 – 微服务端

  1. 创建 微服务项目: micro new --type srv bj38web/service/getCaptcha

    创建完成,会在项目 bj38web 的 service/ 中,多出 getCaptcha 的微服务项目。

  2. 修改密码本 —— getCaptcha/proto/getCaptcha.proto

    syntax = "proto3";
    
    package go.micro.srv.getCaptcha;
    
    service GetCaptcha {
    	rpc Call(Request) returns (Response) {}
    }
    message Request {
    }
    message Response {
    	// 使用切片存储图片信息, 用 json 序列化
    	bytes img = 1;
    }
    复制代码
  3. 编译 proto 文件。 —— make 命令!得到 getCaptcha.micro.go 和 getCaptcha.pb.go

  4. 修改 service/getCaptcha/main.go

import (
	"github.com/micro/go-micro/util/log"
	"github.com/micro/go-micro"
	"bj38web/service/getCaptcha/handler"

	getCaptcha "bj38web/service/getCaptcha/proto/getCaptcha"
)

func main() {
	// New Service
	service := micro.NewService(
		micro.Name("go.micro.srv.getCaptcha"),
		micro.Version("latest"),
	)
	// Register Handler
	getCaptcha.RegisterGetCaptchaHandler(service.Server(), new(handler.GetCaptcha))

	// Run service
	if err := service.Run(); err != nil {
		log.Fatal(err)
	}
}
复制代码
  1. 修改服务发现 : mdns ——> consul
  • 初始化consul

  • 添加 consul 到 micro.NewSerive( )

    consulReg := consul.NewRegistry()
    
    // New Service
    service := micro.NewService(
        micro.Address("192.168.6.108:12341"),  // 防止随机生成 port 
        micro.Name("go.micro.srv.getCaptcha"),
        micro.Registry(consulReg),				// 添加注册
        micro.Version("latest"),
    )
    复制代码
  • 启动 consul , consul agent -dev

  1. 修改 handler/getCaptcha.go 文件,实现生成验证码图片功能
func (e *GetCaptcha) Call(ctx context.Context, req *getCaptcha.Request, rsp *getCaptcha.Response) error {
	// 生成验证码
	cap := captcha.New() // 初始化对象
	cap.SetFont("/Users/yaxuan/go/src/bj38web/service/getCaptcha/conf/comic.ttf") // 设置字体
	cap.SetSize(128, 64) // 设置验证码大小
	cap.SetDisturbance(captcha.MEDIUM) // 设置干扰强度
	cap.SetFrontColor(color.RGBA{0,0,0, 255}) // 设置前景色
	cap.SetBkgColor(color.RGBA{100,0,255, 255}, color.RGBA{255,0,127, 255}, color.RGBA{255,255,10, 255}) // 设置背景色
	img,_ := cap.Create(4,captcha.NUM) // 生成字体
	imgBuf, _ := json.Marshal(img) // 将生成的图片序列化
	rsp.Img = imgBuf // 将imgBuf使用rsp传出
	return nil
}
复制代码

– 将图片验证码功能移植微服务 – web端

  1. 拷贝密码本。 将 service 下的 proto/ 拷贝 web/ 下

  2. 在 GetImageCd() 中 导入包,起别名:

    getCaptcha "bj38web/web/proto/getCaptcha"

  3. 修改GetImageCd函数,调用远程服务

// GetImageCd 获取验证码图片服务
func GetImageCd(ctx *gin.Context) {
	// 获取uuid
	uuid := ctx.Param("uuid")
	fmt.Println(uuid)
	// 调用微服务函数
	microClient := getCaptcha.NewGetCaptchaService("go.micro.srv.getCaptcha", client.DefaultClient)
	resp, err := microClient.Call(context.TODO(), &getCaptcha.Request{})
	if err != nil {
		fmt.Println("未找到远程服务")
	}
	// 将得到的数据反序列化
	var img captcha.Image
	json.Unmarshal(resp.Img, &img)
	// 将图片写出到浏览器
	png.Encode(ctx.Writer, img)
}
复制代码
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享