{"id":479,"date":"2021-06-19T23:20:43","date_gmt":"2021-06-19T15:20:43","guid":{"rendered":"http:\/\/moyisuiying.com\/?p=479"},"modified":"2021-06-19T23:20:43","modified_gmt":"2021-06-19T15:20:43","slug":"java%e5%92%8cpython%e7%9a%84grpc%e8%bf%9c%e7%a8%8b%e8%b0%83%e7%94%a8","status":"publish","type":"post","link":"http:\/\/moyisuiying.com\/index.php\/javastudy\/springboot\/479.html","title":{"rendered":"JAVA\u548cPython\u7684GRPC\u8fdc\u7a0b\u8c03\u7528"},"content":{"rendered":"\n<h2>1.\u4f7f\u7528springboot\u9879\u76ee\u642d\u5efaJava\u7aef<\/h2>\n\n\n\n<h3>1.1pom.xml\u914d\u7f6e\u6587\u4ef6<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?>\n&lt;project xmlns=\"http:\/\/maven.apache.org\/POM\/4.0.0\" xmlns:xsi=\"http:\/\/www.w3.org\/2001\/XMLSchema-instance\"\n         xsi:schemaLocation=\"http:\/\/maven.apache.org\/POM\/4.0.0 https:\/\/maven.apache.org\/xsd\/maven-4.0.0.xsd\">\n    &lt;modelVersion>4.0.0&lt;\/modelVersion>\n    &lt;parent>\n        &lt;groupId>org.springframework.boot&lt;\/groupId>\n        &lt;artifactId>spring-boot-starter-parent&lt;\/artifactId>\n        &lt;version>2.4.3&lt;\/version>\n        &lt;relativePath\/> &lt;!-- lookup parent from repository -->\n    &lt;\/parent>\n    &lt;groupId>com.grpc&lt;\/groupId>\n    &lt;artifactId>server&lt;\/artifactId>\n    &lt;version>0.0.1-SNAPSHOT&lt;\/version>\n    &lt;name>java_server&lt;\/name>\n    &lt;description>JAVa\u7684grpc\u7aef&lt;\/description>\n    &lt;properties>\n        &lt;java.version>11&lt;\/java.version>\n    &lt;\/properties>\n    &lt;dependencies>\n        &lt;dependency>\n            &lt;groupId>org.springframework.boot&lt;\/groupId>\n            &lt;artifactId>spring-boot-starter&lt;\/artifactId>\n        &lt;\/dependency>\n\n        &lt;dependency>\n            &lt;groupId>org.springframework.boot&lt;\/groupId>\n            &lt;artifactId>spring-boot-starter-test&lt;\/artifactId>\n            &lt;scope>test&lt;\/scope>\n        &lt;\/dependency>\n        &lt;dependency>\n            &lt;groupId>io.grpc&lt;\/groupId>\n            &lt;artifactId>grpc-netty-shaded&lt;\/artifactId>\n            &lt;version>1.26.0&lt;\/version>\n        &lt;\/dependency>\n        &lt;dependency>\n            &lt;groupId>io.grpc&lt;\/groupId>\n            &lt;artifactId>grpc-protobuf&lt;\/artifactId>\n            &lt;version>1.26.0&lt;\/version>\n        &lt;\/dependency>\n        &lt;dependency>\n            &lt;groupId>io.grpc&lt;\/groupId>\n            &lt;artifactId>grpc-stub&lt;\/artifactId>\n            &lt;version>1.26.0&lt;\/version>\n        &lt;\/dependency>\n        &lt;!--        lombok\u63d2\u4ef6-->\n        &lt;dependency>\n            &lt;groupId>org.projectlombok&lt;\/groupId>\n            &lt;artifactId>lombok&lt;\/artifactId>\n            &lt;optional>true&lt;\/optional>\n        &lt;\/dependency>\n    &lt;\/dependencies>\n\n    &lt;build>\n        &lt;extensions>\n            &lt;extension>\n                &lt;groupId>kr.motd.maven&lt;\/groupId>\n                &lt;artifactId>os-maven-plugin&lt;\/artifactId>\n                &lt;version>1.6.2&lt;\/version>\n            &lt;\/extension>\n        &lt;\/extensions>\n        &lt;plugins>\n            &lt;plugin>\n                &lt;groupId>org.springframework.boot&lt;\/groupId>\n                &lt;artifactId>spring-boot-maven-plugin&lt;\/artifactId>\n            &lt;\/plugin>\n            &lt;plugin>\n                &lt;groupId>org.xolstice.maven.plugins&lt;\/groupId>\n                &lt;artifactId>protobuf-maven-plugin&lt;\/artifactId>\n                &lt;version>0.6.1&lt;\/version>\n                &lt;configuration>\n                    &lt;protocArtifact>com.google.protobuf:protoc:3.11.0:exe:${os.detected.classifier}&lt;\/protocArtifact>\n                    &lt;pluginId>grpc-java&lt;\/pluginId>\n                    &lt;pluginArtifact>io.grpc:protoc-gen-grpc-java:1.26.0:exe:${os.detected.classifier}&lt;\/pluginArtifact>\n                    &lt;!--\u9ed8\u8ba4\u503c-->\n                    &lt;protoSourceRoot>${project.basedir}\/src\/main\/resources\/proto&lt;\/protoSourceRoot>\n                    &lt;outputDirectory>${project.basedir}\/src\/main\/java\/com\/grpc\/shiyun&lt;\/outputDirectory>\n                    &lt;!--\u8bbe\u7f6e\u662f\u5426\u5728\u751f\u6210java\u6587\u4ef6\u4e4b\u524d\u6e05\u7a7aoutputDirectory\u7684\u6587\u4ef6\uff0c\u9ed8\u8ba4\u503c\u4e3atrue\uff0c\u8bbe\u7f6e\u4e3afalse\u65f6\u4e5f\u4f1a\u8986\u76d6\u540c\u540d\u6587\u4ef6-->\n                    &lt;clearOutputDirectory>true&lt;\/clearOutputDirectory>\n                &lt;\/configuration>\n                &lt;executions>\n                    &lt;execution>\n                        &lt;goals>\n                            &lt;goal>compile&lt;\/goal>\n                            &lt;goal>compile-custom&lt;\/goal>\n                        &lt;\/goals>\n                    &lt;\/execution>\n                &lt;\/executions>\n            &lt;\/plugin>\n        &lt;\/plugins>\n    &lt;\/build>\n\n&lt;\/project><\/code><\/pre>\n\n\n\n<figure class=\"wp-block-image\"><img   class=\"lazyload\" data-src=\"https:\/\/img-blog.csdnimg.cn\/img_convert\/f058982b5a5f47048cb1a2e1c8b52220.png\" src=\"https:\/\/cdn.jsdelivr.net\/gh\/moezx\/cdn@3.0.2\/img\/svg\/loader\/trans.ajax-spinner-preloader.svg\" onerror=\"imgError(this)\"  alt=\"image-20210326195928580\"\/><\/figure >\n<noscript><img src=\"https:\/\/img-blog.csdnimg.cn\/img_convert\/f058982b5a5f47048cb1a2e1c8b52220.png\" alt=\"image-20210326195928580\"\/><\/figure><\/noscript>\n\n\n\n<h3>1.2\u4e66\u5199proto\u6587\u4ef6autochat.proto<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>syntax = \"proto3\";\n\noption java_multiple_files = true;\npackage shiyun;\n\n\/\/ The greeting service definition.\nservice AutoChat {\n  \/\/ Sends a greeting\n  rpc autoChat (AutoChatRequest) returns (AutoChatReply) {}\n}\n\n\/\/ The request message containing the user's name.\nmessage AutoChatRequest {\n  string question = 1;\n}\n\n\/\/ The response message containing the greetings\nmessage AutoChatReply {\n  string response = 1;\n}<\/code><\/pre>\n\n\n\n<h3>1.3\u4f7f\u7528protobuf\u63d2\u4ef6\u751f\u6210Java\u4ee3\u7801<\/h3>\n\n\n\n<p>\u9996\u5148\u70b9\u51fbcompile\u547d\u4ee4\u751f\u6210\u4ee3\u7801\uff0c\u7136\u540e\u518d\u70b9\u51fbcompile-custom\u751f\u6210\u4ee3\u7801\uff0c\u5206\u4e24\u6b21\u751f\u6210\u3002<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img   class=\"lazyload\" data-src=\"https:\/\/img-blog.csdnimg.cn\/img_convert\/820beba9fce8366d7fba900fa73f77f5.png\" src=\"https:\/\/cdn.jsdelivr.net\/gh\/moezx\/cdn@3.0.2\/img\/svg\/loader\/trans.ajax-spinner-preloader.svg\" onerror=\"imgError(this)\"  alt=\"image-20210326200136256\"\/><\/figure >\n<noscript><img src=\"https:\/\/img-blog.csdnimg.cn\/img_convert\/820beba9fce8366d7fba900fa73f77f5.png\" alt=\"image-20210326200136256\"\/><\/figure><\/noscript>\n\n\n\n<figure class=\"wp-block-image\"><img   class=\"lazyload\" data-src=\"https:\/\/img-blog.csdnimg.cn\/img_convert\/aba1f5890f0dd1779a752d7ba3278159.png\" src=\"https:\/\/cdn.jsdelivr.net\/gh\/moezx\/cdn@3.0.2\/img\/svg\/loader\/trans.ajax-spinner-preloader.svg\" onerror=\"imgError(this)\"  alt=\"image-20210326200500587\"\/><\/figure >\n<noscript><img src=\"https:\/\/img-blog.csdnimg.cn\/img_convert\/aba1f5890f0dd1779a752d7ba3278159.png\" alt=\"image-20210326200500587\"\/><\/figure><\/noscript>\n\n\n\n<figure class=\"wp-block-image\"><img   class=\"lazyload\" data-src=\"https:\/\/img-blog.csdnimg.cn\/img_convert\/29cc26823704295bf041a2476e3c5e3b.png\" src=\"https:\/\/cdn.jsdelivr.net\/gh\/moezx\/cdn@3.0.2\/img\/svg\/loader\/trans.ajax-spinner-preloader.svg\" onerror=\"imgError(this)\"  alt=\"image-20210326200538783\"\/><\/figure >\n<noscript><img src=\"https:\/\/img-blog.csdnimg.cn\/img_convert\/29cc26823704295bf041a2476e3c5e3b.png\" alt=\"image-20210326200538783\"\/><\/figure><\/noscript>\n\n\n\n<h2>2.\u4f7f\u7528Python\u751f\u6210\u4ee3\u7801<\/h2>\n\n\n\n<h3>2.1\u5b89\u88c5protobuf<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>pip install grpcio<\/code><\/pre>\n\n\n\n<h3>2.2\u4f7f\u7528 protoc \u7f16\u8bd1 proto \u6587\u4ef6, \u751f\u6210 python \u8bed\u8a00\u7684\u5b9e\u73b0<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code># \u5b89\u88c5 python \u4e0b\u7684 protoc \u7f16\u8bd1\u5668\npip install grpcio-tools<\/code><\/pre>\n\n\n\n<h3>2.3\u7f16\u5199autochat.proto\u6587\u4ef6\uff08\u548cJava\u7684\u4e00\u81f4\uff09<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>syntax = \"proto3\";\n#\u5728Python\u65f6\u5019\u4e0d\u9700\u8981\u8fd9\u4e2a\u9009\u9879\n#option java_multiple_files = true;\npackage shiyun;\n\n\/\/ The greeting service definition.\nservice AutoChat {\n  \/\/ Sends a greeting\n  rpc autoChat (AutoChatRequest) returns (AutoChatReply) {}\n}\n\n\/\/ The request message containing the user's name.\nmessage AutoChatRequest {\n  string question = 1;\n}\n\n\/\/ The response message containing the greetings\nmessage AutoChatReply {\n  string response = 1;\n}<\/code><\/pre>\n\n\n\n<figure class=\"wp-block-image\"><img   class=\"lazyload\" data-src=\"https:\/\/img-blog.csdnimg.cn\/img_convert\/ec0ba57ecddbd2acd7b7150118dea062.png\" src=\"https:\/\/cdn.jsdelivr.net\/gh\/moezx\/cdn@3.0.2\/img\/svg\/loader\/trans.ajax-spinner-preloader.svg\" onerror=\"imgError(this)\"  alt=\"image-20210326202315783\"\/><\/figure >\n<noscript><img src=\"https:\/\/img-blog.csdnimg.cn\/img_convert\/ec0ba57ecddbd2acd7b7150118dea062.png\" alt=\"image-20210326202315783\"\/><\/figure><\/noscript>\n\n\n\n<h3>2.4\u7f16\u8bd1\u6587\u4ef6<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code># \u7f16\u8bd1 proto \u6587\u4ef6\npython -m grpc_tools.protoc --python_out=. --grpc_python_out=. -I. autochat.proto<\/code><\/pre>\n\n\n\n<p><strong>python -m grpc_tools.protoc<\/strong>: python \u4e0b\u7684 protoc \u7f16\u8bd1\u5668\u901a\u8fc7 python \u6a21\u5757(module) \u5b9e\u73b0, \u6240\u4ee5\u8bf4\u8fd9\u4e00\u6b65\u975e\u5e38\u7701\u5fc3<br><strong>--python_out=.<\/strong> : \u7f16\u8bd1\u751f\u6210\u5904\u7406 protobuf \u76f8\u5173\u7684\u4ee3\u7801\u7684\u8def\u5f84, \u8fd9\u91cc\u751f\u6210\u5230\u5f53\u524d\u76ee\u5f55<br>**--grpc_python_out=. : \u7f16\u8bd1\u751f\u6210\u5904\u7406 grpc \u76f8\u5173\u7684\u4ee3\u7801\u7684\u8def\u5f84<\/p>\n\n\n\n<p><strong>-I. autochat.proto<\/strong> : proto \u6587\u4ef6\u7684\u8def\u5f84, \u8fd9\u91cc\u7684 proto \u6587\u4ef6\u5728\u5f53\u524d\u76ee\u5f55<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img   class=\"lazyload\" data-src=\"https:\/\/img-blog.csdnimg.cn\/img_convert\/00362f3063dc5d16089948d077708d05.png\" src=\"https:\/\/cdn.jsdelivr.net\/gh\/moezx\/cdn@3.0.2\/img\/svg\/loader\/trans.ajax-spinner-preloader.svg\" onerror=\"imgError(this)\"  alt=\"image-20210326202330946\"\/><\/figure >\n<noscript><img src=\"https:\/\/img-blog.csdnimg.cn\/img_convert\/00362f3063dc5d16089948d077708d05.png\" alt=\"image-20210326202330946\"\/><\/figure><\/noscript>\n\n\n\n<figure class=\"wp-block-image\"><img   class=\"lazyload\" data-src=\"https:\/\/img-blog.csdnimg.cn\/img_convert\/2909f2023e351a6fd569c5debeb21154.png\" src=\"https:\/\/cdn.jsdelivr.net\/gh\/moezx\/cdn@3.0.2\/img\/svg\/loader\/trans.ajax-spinner-preloader.svg\" onerror=\"imgError(this)\"  alt=\"image-20210326202439991\"\/><\/figure >\n<noscript><img src=\"https:\/\/img-blog.csdnimg.cn\/img_convert\/2909f2023e351a6fd569c5debeb21154.png\" alt=\"image-20210326202439991\"\/><\/figure><\/noscript>\n\n\n\n<h2>3.\u7f16\u5199Java\u5ba2\u6237\u7aef\u4ee3\u7801<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>package com.grpc.client;\nimport io.grpc.ManagedChannel;\nimport io.grpc.ManagedChannelBuilder;\nimport io.grpc.StatusRuntimeException;\nimport shiyun.AutoChatRequest;\n\nimport java.util.concurrent.TimeUnit;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\n\npublic class AutoChatClient {\n    private static final Logger logger = Logger.getLogger(AutoChatClient.class.getName());\n\n    private final ManagedChannel channel;\n    private final shiyun.AutoChatGrpc.AutoChatBlockingStub blockingStub;\n\n    \/**\n     * Construct client connecting to HelloWorld server at {@code host:port}.\n     *\/\n    public AutoChatClient(String host, int port) {\n        this(ManagedChannelBuilder.forAddress(host, port)\n                \/\/ Channels are secure by default (via SSL\/TLS). For the example we disable TLS to avoid\n                \/\/ needing certificates.\n                .usePlaintext()\n                .build());\n    }\n\n    \/**\n     * Construct client for accessing HelloWorld server using the existing channel.\n     *\/\n    AutoChatClient(ManagedChannel channel) {\n        this.channel = channel;\n        blockingStub = shiyun.AutoChatGrpc.newBlockingStub(channel);\n    }\n\n    public void shutdown() throws InterruptedException {\n        channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);\n    }\n\n    \/**\n     * Say hello to server.\n     *\/\n    public void sendQuestion(String question) {\n        AutoChatRequest request = shiyun.AutoChatRequest.newBuilder().setQuestion(question).build();\n        shiyun.AutoChatReply response;\n        try {\n            response = blockingStub.autoChat(request);\n            logger.info(\"\u63a5\u6536\u6765\u81ea\u670d\u52a1\u5668\u7684\u54cd\u5e94: \" + response.getResponse());\n        } catch (StatusRuntimeException e) {\n            logger.log(Level.WARNING, \"RPC failed: {0}\", e.getStatus());\n            return;\n        }\n\n    }\n\n    \/**\n     * Greet server. If provided, the first element of {@code args} is the name to use in the\n     * greeting.\n     *\/\n    public static void main(String&#91;] args) throws Exception {\n        \/\/ Access a service running on the local machine on port 50052\n        AutoChatClient client = new AutoChatClient(\"localhost\", 50052);\n        try {\n            String user = \"world\";\n            \/\/ Use the arg as the name to greet if provided\n            if (args.length > 0) {\n                user = args&#91;0];\n            }\n            int i = 0 ;\n           while (true){\n               client.sendQuestion(user+i++);\n               Thread.sleep(1000);\n           }\n        } finally {\n            client.shutdown();\n        }\n    }\n}<\/code><\/pre>\n\n\n\n<h2>4.Python\u670d\u52a1\u7aef\u4ee3\u7801<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>from concurrent import futures\nimport time\nimport grpc\n\n# \u5b9e\u73b0 proto \u6587\u4ef6\u4e2d\u5b9a\u4e49\u7684 AutoChatServicer\nimport autochat_pb2_grpc, autochat_pb2\n\n_ONE_DAY_IN_SECONDS = 60 * 60 * 24\n\n\nclass AutoChatServer(autochat_pb2_grpc.AutoChatServicer):\n    def autoChat(self, request, context):\n        print(\"\u63a5\u6536\u5230\u5ba2\u6237\u7aef\u6d88\u606f\uff1a\" + request.question)\n        return autochat_pb2.AutoChatReply(response= request.question)\n\n\ndef serve():\n    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))\n    autochat_pb2_grpc.add_AutoChatServicer_to_server(AutoChatServer(), server)\n    server.add_insecure_port('&#91;::]:50052')\n    print(\"\u542f\u52a8\u670d\u52a1\u5668\u7b49\u5f85\u8fde\u63a5\u3002\u3002\u3002\u3002\")\n    server.start()\n    try:\n        while True:\n            time.sleep(_ONE_DAY_IN_SECONDS)\n    except KeyboardInterrupt:\n        server.stop(0)\n\n\nif __name__ == '__main__':\n    serve()<\/code><\/pre>\n\n\n\n<h2>5.\u9879\u76ee\u6e90\u4ee3\u7801\u5df2\u7ecf\u540c\u6b65\u5230GitHub\u548cgitee\uff0c\u5982\u6709\u9700\u8981\u8bf7\u79fb\u6b65\u81ea\u884c\u4e0b\u8f7d\uff1a<\/h2>\n\n\n\n<h3>gitee: <a href=\"https:\/\/gitee.com\/ljf2402901363\/grpc.git\" target=\"_blank\"  rel=\"nofollow\" >https:\/\/gitee.com\/ljf2402901363\/grpc.git<\/a><\/h3>\n\n\n\n<h3>github: <a href=\"https:\/\/github.com\/LJF2402901363\/grpc.git\" target=\"_blank\"  rel=\"nofollow\" >https:\/\/github.com\/LJF2402901363\/grpc.git<\/a><\/h3>\n","protected":false},"excerpt":{"rendered":"<p>1.\u4f7f\u7528springboot\u9879\u76ee\u642d\u5efaJava\u7aef 1.1pom.xml\u914d\u7f6e\u6587\u4ef6 1.2\u4e66\u5199proto\u6587\u4ef6autochat.proto &#8230;<\/p>","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[202],"tags":[216,217,218,60,148],"_links":{"self":[{"href":"http:\/\/moyisuiying.com\/index.php\/wp-json\/wp\/v2\/posts\/479"}],"collection":[{"href":"http:\/\/moyisuiying.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/moyisuiying.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/moyisuiying.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"http:\/\/moyisuiying.com\/index.php\/wp-json\/wp\/v2\/comments?post=479"}],"version-history":[{"count":1,"href":"http:\/\/moyisuiying.com\/index.php\/wp-json\/wp\/v2\/posts\/479\/revisions"}],"predecessor-version":[{"id":480,"href":"http:\/\/moyisuiying.com\/index.php\/wp-json\/wp\/v2\/posts\/479\/revisions\/480"}],"wp:attachment":[{"href":"http:\/\/moyisuiying.com\/index.php\/wp-json\/wp\/v2\/media?parent=479"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/moyisuiying.com\/index.php\/wp-json\/wp\/v2\/categories?post=479"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/moyisuiying.com\/index.php\/wp-json\/wp\/v2\/tags?post=479"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}