go微服务系列之二

wiatingpub · · 1314 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

这是使用gomicro开发微服务系列的第二篇,在上一篇中我只是使用了user-srv和web-srv实现了一个demo,在这里我将实用consul实现服务发现。如果想直接查阅源码或者通过demo学习的,可以访问[ricoder_demo](https://github.com/wiatingpub/demo)。 如何编写一个微服务?这里用的是go的微服务框架go micro,具体的情况可以查阅:http://btfak.com/%E5%BE%AE%E6%9C%8D%E5%8A%A1/2016/03/28/go-micro/ ##### 一、如何安装consul 我的开发系统采用的是ubunt16.04,这里就给出ubuntu下安装consul的步骤: ```bash $ wget https://releases.hashicorp.com/consul/0.7.2/consul_0.7.2_linux_amd64.zip $ sudo apt-get install unzip $ ls $ unzip consul_0.7.2_linux_amd64.zip $ sudo mv consul /usr/local/bin/consul $ wget https://releases.hashicorp.com/consul/0.7.2/consul_0.7.2_web_ui.zip $ unzip consul_0.7.2_web_ui.zip $ mkdir -p /usr/share/consul $ mv dist /usr/share/consul/ui ``` Consul 压缩包地址:<https://www.consul.io/downloads.html> 验证安装是否成功的方法: ```basic $ consul Usage: consul [--version] [--help] <command> [<args>] Available commands are: agent Runs a Consul agent catalog Interact with the catalog event Fire a new event exec Executes a command on Consul nodes force-leave Forces a member of the cluster to enter the "left" state info Provides debugging information for operators. join Tell Consul agent to join cluster keygen Generates a new encryption key keyring Manages gossip layer encryption keys kv Interact with the key-value store leave Gracefully leaves the Consul cluster and shuts down lock Execute a command holding a lock maint Controls node or service maintenance mode members Lists the members of a Consul cluster monitor Stream logs from a Consul agent operator Provides cluster-level tools for Consul operators reload Triggers the agent to reload configuration files rtt Estimates network round trip time between nodes snapshot Saves, restores and inspects snapshots of Consul server state validate Validate config files/directories version Prints the Consul version watch Watch for changes in Consul ``` 启动consul服务的方法: ```bash $ consul agent -dev ==> Starting Consul agent... ==> Consul agent running! Version: 'v0.9.3' Node ID: '199ee0e9-db61-f789-b22a-b6b472f63fbe' Node name: 'ricoder' Datacenter: 'dc1' (Segment: '<all>') Server: true (Bootstrap: false) Client Addr: 127.0.0.1 (HTTP: 8500, HTTPS: -1, DNS: 8600) Cluster Addr: 127.0.0.1 (LAN: 8301, WAN: 8302) ``` 优雅的停止服务的方法: 命令:CTRL+C 其他命令: - consul members:查看集群成员 - consul info:查看当前服务器的状况 - consul leave:退出当前服务集群 成功开启consul服务后可以登录后台访问地址:[http://localhost:8500](http://localhost:8500/),如下: ![Screenshot from 2017-10-14 13-35-58.png](http://upload-images.jianshu.io/upload_images/3365849-aaca166301514e77.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) #### 二、api-srv的开发,实现动态路由 根据官方对api-srv的介绍:The **micro api** is an API gateway for microservices. Use the API gateway [pattern](http://microservices.io/patterns/apigateway.html) to provide a single entry point for your services. The micro api serves HTTP and dynamically routes to the appropriate backend service. 粗略翻译的意思就是:api-srv是微服务的网关,使用API网关模式可以为我们的服务提供一个入口,api-srv提供HTTP服务,并动态路由到相应的后端服务。 步骤1:监听8082端口,并绑定handler处理http请求 ```go mux := http.NewServeMux() mux.HandleFunc("/", handleRPC) log.Println("Listen on :8082") http.ListenAndServe(":8082", mux) ``` 步骤2:实现handler,并实现跨域处理 ```go if r.URL.Path == "/" { w.Write([]byte("ok,this is the server ...")) return } // 跨域处理 if origin := r.Header.Get("Origin"); cors[origin] { w.Header().Set("Access-Control-Allow-Origin", origin) } else if len(origin) > 0 && cors["*"] { w.Header().Set("Access-Control-Allow-Origin", origin) } w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS") w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-Token, X-Client") w.Header().Set("Access-Control-Allow-Credentials", "true") if r.Method == "OPTIONS" { return } if r.Method != "POST" { http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) return } ``` 步骤3:实现将url转换为service和method,这里我采用了pathToReceiver这个函数来处理 ```go p = path.Clean(p) p = strings.TrimPrefix(p, "/") parts := strings.Split(p, "/") // If we've got two or less parts // Use first part as service // Use all parts as method if len(parts) <= 2 { service := ns + strings.Join(parts[:len(parts)-1], ".") method := strings.Title(strings.Join(parts, ".")) return service, method } // Treat /v[0-9]+ as versioning where we have 3 parts // /v1/foo/bar => service: v1.foo method: Foo.bar if len(parts) == 3 && versionRe.Match([]byte(parts[0])) { service := ns + strings.Join(parts[:len(parts)-1], ".") method := strings.Title(strings.Join(parts[len(parts)-2:], ".")) return service, method } // Service is everything minus last two parts // Method is the last two parts service := ns + strings.Join(parts[:len(parts)-2], ".") method := strings.Title(strings.Join(parts[len(parts)-2:], ".")) return service, method ``` http传进来的url是http://127.0.0.1:8082/user/userService/SelectUser,我在handler中通过以下方式调用后: ``` service, method := apid.PathToReceiver(config.Namespace, r.URL.Path) ``` service和method分别是: ```bash 2017/10/14 13:56:12 service:com.class.cinema.user 2017/10/14 13:56:12 method:UserService.SelectUser ``` 注意:var config.Namespace = "com.class.cinema" 步骤4:封装request,调用服务 ```go br, _ := ioutil.ReadAll(r.Body) request := json.RawMessage(br) var response json.RawMessage req := (*cmd.DefaultOptions().Client).NewJsonRequest(service, method, &request) ctx := apid.RequestToContext(r) err := (*cmd.DefaultOptions().Client).Call(ctx, req, &response) ``` 在这里Call就是调用相应服务的关键。 步骤5:对err进行相应的处理和返回调用结果 ```go // make the call if err != nil { ce := microErrors.Parse(err.Error()) switch ce.Code { case 0: // assuming it's totally screwed ce.Code = 500 ce.Id = service ce.Status = http.StatusText(500) // ce.Detail = "error during request: " + ce.Detail w.WriteHeader(500) default: w.WriteHeader(int(ce.Code)) } w.Write([]byte(ce.Error())) return } b, _ := response.MarshalJSON() w.Header().Set("Content-Length", strconv.Itoa(len(b))) w.Write(b) ``` 通过对err的处理,在请求的method或者service不存在时,如: ![Screenshot from 2017-10-14 14-05-28.png](http://upload-images.jianshu.io/upload_images/3365849-4246811991514bde.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 会有相应的错误信息提示返回到客户端。 #### 三、跑起服务,查看效果 步骤1:首先要先跑起consul服务发现机制,这样后期加入的服务才可以被检测到,如: ![Screenshot from 2017-10-14 14-34-13.png](http://upload-images.jianshu.io/upload_images/3365849-13f381a81f14ffd4.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 步骤2:跑起user-srv服务,如: ![Screenshot from 2017-10-14 14-35-36.png](http://upload-images.jianshu.io/upload_images/3365849-b776214cc97f61a9.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 登录consul后台,查看服务是否被发现: ![Screenshot from 2017-10-14 14-36-41.png](http://upload-images.jianshu.io/upload_images/3365849-c0ea33e7aa04bb97.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 可以从中看到多了一个com.class.cinema.user这个服务 步骤3:通过postman访问user-srv服务 ![Screenshot from 2017-10-14 14-39-37.png](http://upload-images.jianshu.io/upload_images/3365849-828ef2aec8e2fd86.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 可以看到在Body处有数据显示出来了,再看看服务后台的日志输出 ![Screenshot from 2017-10-14 14-40-12.png](http://upload-images.jianshu.io/upload_images/3365849-92220b97d628b546.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ![Screenshot from 2017-10-14 14-40-29.png](http://upload-images.jianshu.io/upload_images/3365849-d28adc5aa48c36a0.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 由上面两个图可以看出来,客户端的请求到达了api-srv,再通过api-srv到达了user-srv。 注意:此处的url的书写曾经遇见过一个bug,那就是我第一次书写成了 http://127.0.0.1:8082/user/SelectUser,导致出现这种异常: ![Screenshot from 2017-10-14 14-44-35.png](http://upload-images.jianshu.io/upload_images/3365849-ec43d0e83de2c4f4.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) **有兴趣的可以关注我的个人公众号 ~** ![qrcode_for_gh_04e57fbebd02_258.jpg](http://upload-images.jianshu.io/upload_images/3365849-f14ff503e4288fc3.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

有疑问加站长微信联系(非本文作者))

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

1314 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传