微服務的調用
調用的代碼來自大神:go-micro V2 從零開始(一)使用micro工具自動生成項目
上一期我們的把我們的服務注冊到了我們的Consul中,怎么去使用客戶端代碼的形式去調用微服務吶?
package main
import (
"context"
"github.com/micro/go-micro/v2"
"github.com/micro/go-micro/v2/client"
pb "greeter/proto/greeter"
"log"
)
func main() {
// 這里以HelloService默認提供的Call接口調用為例示范服務的調用
// 可以看到他的調用就像調用本地方法一樣,go-micro為我們隱藏了背后的服務注冊、發現、負載均衡以及網絡操作
testCallFunc()
// 這里示范消息的發送
testSendMessage()
}
func testCallFunc(){
// 獲取hello服務
// 這里第一個參數"go.micro.service.hello"必須與hello-service注冊信息一致
// 一般由micro生成的項目默認服務名為:{namespace 默認[go.micro]}.{type 默認[service]}.{項目名}組成
// 如果要修改默認值,在生成項目時可以這樣: micro --namespace=XXX --type=YYYY ZZZZ
// 當然也可以直接修改main.go中micro.Name("go.micro.service.hello")的內容
helloService := pb.NewGreeterService("go.micro.service.greeter", client.DefaultClient)
// 默認生成的hello服務中自帶三個接口: Call() Stream() PingPong(),分別對應參數調用、流傳輸和心跳
resp, err := helloService.Call(context.Background(), &pb.Request{
Name: "xiao xie",
})
if err != nil {
log.Panic("call func", err)
}
log.Println("call func success!", resp.Msg)
}
func testSendMessage(){
// 消息主題,定義規則與服務一致
// 同樣,也可以修改main.go的micro.RegisterSubscriber("go.micro.service.hello", service.Server(), new(subscriber.Hello))
const topic = "go.micro.service.greeter"
// 獲取消息發送接口,這里我一直使用的時micro.NewPublisher()
// 但在寫文時發現NewPublisher()已經被廢止,改為NewEvent(),二者參數和返回值一致
event := micro.NewEvent(topic, client.DefaultClient)
if err := event.Publish(context.Background(), &pb.Message{
Say: "hello server!",
}); err != nil {
log.Panic("send msg", err)
}
log.Println("send msg success!")
}
注意點我們的客戶端是放在微服務的目錄下:
image.png
結果悲劇了:
D:\code\go\Mi_Onse\greeter>go run greeter_cli.go
2021-01-20 17:22:20.086552 I | call func{"id":"go.micro.client","code":500,"detail":"service go.micro.service.greeter: not found","status":"Internal Server Error"}
panic: call func{"id":"go.micro.client","code":500,"detail":"service go.micro.service.greeter: not found","status":"Internal Server Error"}
goroutine 1 [running]:
log.Panic(0xc0004b1f48, 0x2, 0x2)
D:/go1.14/go1.14.13/src/log/log.go:351 +0xb3
main.testCallFunc()
D:/code/go/Mi_Onse/greeter/greeter_cli.go:33 +0x18a
main.main()
D:/code/go/Mi_Onse/greeter/greeter_cli.go:15 +0x27
exit status 2
D:\code\go\Mi_Onse\greeter>
原因是我們的客戶端調用的時候應該是需要去我們的Consul查詢我們的服務,所以它找不到了!!!
這個地方也是找不到注冊到consul的的服務:
D:\code\go\Mi_Onse>micro list services
D:\code\go\Mi_Onse>
我們切換我們的微服務注冊到默認的MDNS
切換后,查看服務:
D:\code\go\Mi_Onse>micro list services
go.micro.service.greeter
micro.http.broker
- 從consul查看服務列表--方式1:
–registry_address=127.0.0.1:8500 用來指定服務發現的地址, 就是上面的 consul 的地址, consul 默認端口是 8500
這地方也不行?暫時不知道!!!備注一下 也獲取不到!!!
D:\code\go\Mi_Onse>micro --registry_address=127.0.0.1:8500 list services
D:\code\go\Mi_Onse>
- 從consul查看服務列表--方式2:
這地方也不行?暫時不知道!!!備注一下 也獲取不到!!!
D:\code\go\Mi_Onse>micro --registry consul --registry_address loaclhost:8500 list services
Registry consul not found
D:\code\go\Mi_Onse>
先切換回 使用默認的MDSN 啟動微服務方式:
再調用我們的客戶端代碼:
D:\code\go\Mi_Onse\greeter>go run greeter_cli.go
2021-01-20 17:30:43.456834 I | call func success! Hello xiao xie
2021-01-20 17:30:43.558562 I | send msg success!
D:\code\go\Mi_Onse\greeter>
補充 :其他命令學習
1 查看服務詳情:
命令:
D:\code\go\Mi_Onse>micro get service go.micro.service.greeter
結果:
D:\code\go\Mi_Onse>micro get service go.micro.service.greeter
service go.micro.service.greeter
version latest
ID Address Metadata
go.micro.service.greeter-c344efa6-8a4f-4674-9fe1-f1679e667233 192.168.1.213:52927 broker=http,protocol=grpc,registry=mdns,server=grpc,transport=grpc
Endpoint: Greeter.Call
Request: {
message_state MessageState {
no_unkeyed_literals NoUnkeyedLiterals
do_not_compare DoNotCompare
do_not_copy DoNotCopy
message_info MessageInfo
}
int32 int32
unknown_fields []uint8
name string
}
Response: {
message_state MessageState {
no_unkeyed_literals NoUnkeyedLiterals
do_not_compare DoNotCompare
do_not_copy DoNotCopy
message_info MessageInfo
}
int32 int32
unknown_fields []uint8
msg string
}
Endpoint: Greeter.PingPong
Metadata: stream=true
Request: {}
Response: {}
Endpoint: Greeter.Stream
Metadata: stream=true
Request: {}
Response: {}
Endpoint: Greeter.Handle
Metadata: subscriber=true,topic=go.micro.service.greeter
Request: {
message_state MessageState {
no_unkeyed_literals NoUnkeyedLiterals
do_not_compare DoNotCompare
do_not_copy DoNotCopy
message_info MessageInfo
}
int32 int32
unknown_fields []uint8
say string
}
Response: {}
2 嘗試調用服務:
- 估計這個是v1版本的形式:
D:\code\go\Mi_Onse>micro query go.micro.service.greeter greeter.call
無效參數
QUERY { PROCESS | SESSION | TERMSERVER | USER }
exit status 1
- V2版本的相識(當我們的把微服務注冊到Consul的時候是找不到服務的)
D:\code\go\Mi_Onse>micro call go.micro.service.greeter greeter.call
error calling go.micro.service.greeter.greeter.call: {"id":"go.micro.client","code":500,"detail":"service go.micro.service.greeter: not found","status":"Internal Server Error"}
D:\code\go\Mi_Onse>
切換回默認注冊到MDNS的之后【區分大小寫:】
大寫:
D:\code\go\Mi_Onse>micro call go.micro.service.greeter Greeter.Call
{
"msg": "Hello "
}
小寫:
D:\code\go\Mi_Onse>micro call go.micro.service.greeter greeter.call
error calling go.micro.service.greeter.greeter.call: {"id":"go.micro.client","code":500,"detail":"unknown service greeter","status":"Internal Server Error"}
使用Mirco修改默認注冊中心:
D:\code\go\Mi_Onse>set MICRO_REGISRY consul
MICRO_REGISRY=consul
D:\code\go\Mi_Onse>set MIRCO_REGISTRY_ADDRESS 127.0.0.1:8500
環境變量 MIRCO_REGISTRY_ADDRESS 127.0.0.1:8500 沒有定義
D:\code\go\Mi_Onse>
cli命令:
D:\code\go\Mi_Onse>micro cli
micro> list
go.micro.service.greeter
micro.http.broker
micro> help
Commands:
call Call a service
deregister Deregister a service
exit Exit the CLI
get Get service info
health Get service health
help CLI usage
list List services, peers or routes
publish Publish a message to a topic
quit Exit the CLI
register Register a service
stats Get service stats
stream Stream a call to a service
micro>
嘗試修改我們的mirco 默認的注冊中心
D:\code\go\Mi_Onse>micro --registry consul --registry_address loaclhost:8500 list services
Registry consul not found
D:\code\go\Mi_Onse>micro --registry consul --registry_address loaclhost:8500 list services
Registry consul not found
D:\code\go\Mi_Onse>
V2 micro --help 命令大全:
D:\code\go\Mi_Onse>micro --help
NAME:
micro - A microservice runtime
Use `micro [command] --help` to see command specific help.
USAGE:
micro [global options] command [command options] [arguments...]
VERSION:
latest
COMMANDS:
server Run the micro server
new Create a service template
env Get/set micro cli environment
login Login using a token
run Run a service: micro run [source]
logs Get logs for a service
call Call a service e.g micro call greeter Say.Hello '{"name": "John"}
update Update a service: micro update [source]
kill Kill a service: micro kill [source]
store Run the micro store service
config Manage configuration values
auth Manage authentication related resources
status List runtime objects
stream Create a service stream
file Move files between your local machine and the server
list List items in registry or network
cli Run the interactive CLI
publish Publish a message to a topic
stats Query the stats of a service
bot Run the chatops bot
whoami Account information
api Run the api gateway
register Register an item in the registry
deregister Deregister an item in the registry
get Get item from registry
broker Run the message broker
health Check the health of a service
proxy Run the service proxy
router Run the micro network router
tunnel Run the micro network tunnel
network Run the micro network node
registry Run the service registry
debug Run the micro debug service
trace Get tracing info from a service
runtime Run the micro runtime
service Run a micro service
plugin Plugin commands
web Run the web dashboard
init Run the micro operator
help, h Shows a list of commands or help for one command
GLOBAL OPTIONS:
--client value Client for go-micro; rpc [%MICRO_CLIENT%]
--client_request_timeout value Sets the client request timeout. e.g 500ms, 5s, 1m. Default: 5s [%MICRO_CLIENT_REQUEST_TIMEOUT%]
--client_retries value Sets the client retries. Default: 1 (default: 1) [%MICRO_CLIENT_RETRIES%]
--client_pool_size value Sets the client connection pool size. Default: 1 (default: 0) [%MICRO_CLIENT_POOL_SIZE%]
--client_pool_ttl value Sets the client connection pool ttl. e.g 500ms, 5s, 1m. Default: 1m [%MICRO_CLIENT_POOL_TTL%]
--register_ttl value Register TTL in seconds (default: 60) [%MICRO_REGISTER_TTL%]
--register_interval value Register interval in seconds (default: 30) [%MICRO_REGISTER_INTERVAL%]
--server value Server for go-micro; rpc [%MICRO_SERVER%]
--server_name value Name of the server. go.micro.srv.example [%MICRO_SERVER_NAME%]
--server_version value Version of the server. 1.1.0 [%MICRO_SERVER_VERSION%]
--server_id value Id of the server. Auto-generated if not specified [%MICRO_SERVER_ID%]
--server_address value Bind address for the server. 127.0.0.1:8080 [%MICRO_SERVER_ADDRESS%]
--server_advertise value Used instead of the server_address when registering with discovery. 127.0.0.1:8080 [%MICRO_SERVER_ADVERTISE%]
--server_metadata value A list of key-value pairs defining metadata. version=1.0.0 [%MICRO_SERVER_METADATA%]
--broker value Broker for pub/sub. http, nats, rabbitmq [%MICRO_BROKER%]
--broker_address value Comma-separated list of broker addresses [%MICRO_BROKER_ADDRESS%]
--profile value Debug profiler for cpu and memory stats [%MICRO_DEBUG_PROFILE%]
--registry value Registry for discovery. etcd, mdns [%MICRO_REGISTRY%]
--registry_address value Comma-separated list of registry addresses [%MICRO_REGISTRY_ADDRESS%]
--runtime value Runtime for building and running services e.g local, kubernetes (default: "local") [%MICRO_RUNTIME%]
--runtime_source value Runtime source for building and running services e.g github.com/micro/service (default: "github.com/micro/services") [%MICRO_RUNTIME_SOURCE%]
--selector value Selector used to pick nodes for querying [%MICRO_SELECTOR%]
--store value Store used for key-value storage [%MICRO_STORE%]
--store_address value Comma-separated list of store addresses [%MICRO_STORE_ADDRESS%]
--store_database value Database option for the underlying store [%MICRO_STORE_DATABASE%]
--store_table value Table option for the underlying store [%MICRO_STORE_TABLE%]
--transport value Transport mechanism used; http [%MICRO_TRANSPORT%]
--transport_address value Comma-separated list of transport addresses [%MICRO_TRANSPORT_ADDRESS%]
--tracer value Tracer for distributed tracing, e.g. memory, jaeger [%MICRO_TRACER%]
--tracer_address value Comma-separated list of tracer addresses [%MICRO_TRACER_ADDRESS%]
--auth value Auth for role based access control, e.g. service [%MICRO_AUTH%]
--auth_id value Account ID used for client authentication [%MICRO_AUTH_ID%]
--auth_secret value Account secret used for client authentication [%MICRO_AUTH_SECRET%]
--auth_namespace value Namespace for the services auth account (default: "go.micro") [%MICRO_AUTH_NAMESPACE%]
--auth_public_key value Public key for JWT auth (base64 encoded PEM) [%MICRO_AUTH_PUBLIC_KEY%]
--auth_private_key value Private key for JWT auth (base64 encoded PEM) [%MICRO_AUTH_PRIVATE_KEY%]
--auth_provider value Auth provider used to login user [%MICRO_AUTH_PROVIDER%]
--auth_provider_client_id value The client id to be used for oauth [%MICRO_AUTH_PROVIDER_CLIENT_ID%]
--auth_provider_client_secret value The client secret to be used for oauth [%MICRO_AUTH_PROVIDER_CLIENT_SECRET%]
--auth_provider_endpoint value The enpoint to be used for oauth [%MICRO_AUTH_PROVIDER_ENDPOINT%]
--auth_provider_redirect value The redirect to be used for oauth [%MICRO_AUTH_PROVIDER_REDIRECT%]
--auth_provider_scope value The scope to be used for oauth [%MICRO_AUTH_PROVIDER_SCOPE%]
--config value The source of the config to be used to get configuration [%MICRO_CONFIG%]
--local Enable local only development: Defaults to true. (default: false)
--enable_acme Enables ACME support via Let's Encrypt. ACME hosts should also be specified. (default: false) [%MICRO_ENABLE_ACME%]
--acme_hosts value Comma separated list of hostnames to manage ACME certs for [%MICRO_ACME_HOSTS%]
--acme_provider value The provider that will be used to communicate with Let's Encrypt. Valid options: autocert, certmagic [%MICRO_ACME_PROVIDER%]
--enable_tls Enable TLS support. Expects cert and key file to be specified (default: false) [%MICRO_ENABLE_TLS%]
--tls_cert_file value Path to the TLS Certificate file [%MICRO_TLS_CERT_FILE%]
--tls_key_file value Path to the TLS Key file [%MICRO_TLS_KEY_FILE%]
--tls_client_ca_file value Path to the TLS CA file to verify clients against [%MICRO_TLS_CLIENT_CA_FILE%]
--api_address value Set the api address e.g 0.0.0.0:8080 [%MICRO_API_ADDRESS%]
--namespace value Set the micro service namespace (default: "micro") [%MICRO_NAMESPACE%]
--proxy_address value Proxy requests via the HTTP address specified [%MICRO_PROXY_ADDRESS%]
--web_address value Set the web UI address e.g 0.0.0.0:8082 [%MICRO_WEB_ADDRESS%]
--network value Set the micro network name: local, go.micro [%MICRO_NETWORK%]
--network_address value Set the micro network address e.g. :9093 [%MICRO_NETWORK_ADDRESS%]
--router_address value Set the micro router address e.g. :8084 [%MICRO_ROUTER_ADDRESS%]
--gateway_address value Set the micro default gateway address e.g. :9094 [%MICRO_GATEWAY_ADDRESS%]
--tunnel_address value Set the micro tunnel address e.g. :8083 [%MICRO_TUNNEL_ADDRESS%]
--api_handler value Specify the request handler to be used for mapping HTTP requests to services; {api, proxy, rpc} [%MICRO_API_HANDLER%]
--api_namespace value Set the namespace used by the API e.g. com.example.api [%MICRO_API_NAMESPACE%]
--web_namespace value Set the namespace used by the Web proxy e.g. com.example.web [%MICRO_WEB_NAMESPACE%]
--web_url value Set the host used for the web dashboard e.g web.example.com [%MICRO_WEB_HOST%]
--enable_stats Enable stats (default: false) [%MICRO_ENABLE_STATS%]
--auto_update Enable automatic updates (default: false) [%MICRO_AUTO_UPDATE%]
--update_url value Set the url to retrieve system updates from (default: "https://go.micro.mu/update") [%MICRO_UPDATE_URL%]
--report_usage Report usage statistics (default: true) [%MICRO_REPORT_USAGE%]
--env value, -e value Override environment [%MICRO_ENV%]
--plugin value Comma separated list of plugins e.g broker/rabbitmq, registry/etcd, micro/basic_auth, /path/to/plugin.so [%MICRO_PLUGIN%]
--help, -h show help (default: false)
--version print the version (default: false)
D:\code\go\Mi_Onse>
區別:
D:\code\go\Mi_Onse\greeter>micro register consulsdasda
D:\code\go\Mi_Onse\greeter>micro register consulsdasdaasdasd
D:\code\go\Mi_Onse>micro --registry consul --registry_address loaclhost:8500 list services
Registry consul not found