美文网首页
GO 微服务GO-Micro(8)-纯个人学习笔记记录:使用代码

GO 微服务GO-Micro(8)-纯个人学习笔记记录:使用代码

作者: 小钟钟同学 | 来源:发表于2021-01-21 10:11 被阅读0次

    微服务的调用

    调用的代码来自大神: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
    

    相关文章

      网友评论

          本文标题:GO 微服务GO-Micro(8)-纯个人学习笔记记录:使用代码

          本文链接:https://www.haomeiwen.com/subject/uhikzktx.html