一、如何安装consul
我的开发系统采用的是ubunt16.04,这里就给出ubuntu下安装consul的步骤:
$ wget
$ sudo apt-get install unzip
$ ls
$ unzip consul_0.7.2_linux_amd64.zip
$ sudo mv consul /usr/local/bin/consul
$ wget
$ unzip consul_0.7.2_web_ui.zip
$ mkdir -p /usr/share/consul
$ mv dist /usr/share/consul/ui
验证安装是否成功的方法:
$ 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服务的方法:
$ 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:退出当前服务集群
二、api-srv的开发,实现动态路由
mux := http.NewServeMux()
mux.HandleFunc("/", handleRPC)
log.Println("Listen on :8082")
http.ListenAndServe(":8082", mux)
步骤2:实现handler,并实现跨域处理
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这个函数来处理
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
service, method := apid.PathToReceiver(config.Namespace, r.URL.Path)
service和method分别是:
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,调用服务
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进行相应的处理和返回调用结果
// 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会有相应的错误信息提示返回到客户端。
三、跑起服务,查看效果
步骤1:首先要先跑起consul服务发现机制,这样后期加入的服务才可以被检测到,如:
Screenshot from 2017-10-14 14-34-13.png步骤2:跑起user-srv服务,如:
Screenshot from 2017-10-14 14-35-36.png登录consul后台,查看服务是否被发现:
Screenshot from 2017-10-14 14-36-41.png可以从中看到多了一个com.class.cinema.user这个服务
步骤3:通过postman访问user-srv服务
Screenshot from 2017-10-14 14-39-37.png可以看到在Body处有数据显示出来了,再看看服务后台的日志输出
Screenshot from 2017-10-14 14-40-12.png Screenshot from 2017-10-14 14-40-29.png由上面两个图可以看出来,客户端的请求到达了api-srv,再通过api-srv到达了user-srv。
Screenshot from 2017-10-14 14-44-35.png有兴趣的可以关注我的个人公众号 ~
qrcode_for_gh_04e57fbebd02_258.jpg