First, preface
A while ago about. NET's major public numbers have published information about GRPC, and it comes with a wave of tutorials on how to use it in. NET core, but in many of these tutorials it's mostly generic and difficult to actually use in the real world, and the tutorial is GRPC-based, but uses its SSL/TLS , so more in line with the actual production use, the period will also be supporting the explanation docker, OpenSSL and so on.
Second, the service side
A. Preparatory work
The author's project is divided into three sections as follows:
Sino.GrpcService.Host (console): Host program
Sino.GrpcService.Impl (class Library): Implementing Protocols
Sino.GrpcService.Protocol (class Library): Build protocol
The final project looks like this:
The Project.json for each project are as follows:
View Code
where "buildoptions" and "publishoptions" we will include the certificates we need later in the output and release, where we also use the "configuration" related components to read configuration information.
Sino.GrpcService.Impl:
View Code
Where we installed the "mongodb.driver", in order to be able to close to the real situation, the author uses MongoDb as a data source to provide data, of course, readers in order to be able to quickly get started can hard code some data.
Sino.GrpcService.Protocol:
View Code
This completes the initialization of the project.
B. Writing an agreement
First we open the Sino.GrpcService.Protocol project, create a new Msg.proto file in it, open the Msg.proto file, in which we will write the Proto3 language-based protocol so that it can be automatically generated later in the language, if the reader needs more in-depth learning to open the site Proto3 language Guide.
Here we define that we are currently using the Proto3 language and the package name (born into C # then the namespace) is:
Syntax = "Proto3";p ackage Sino.grpcservice;
The author defines 1 services for the service, and there are 4 ways to do this:
Service msgservice{ RPC GetList (getmsglistrequest) returns (Getmsglistreply) {} RPC GetOne (getmsgonerequest) Returns (Getmsgonereply) {} RPC Edit (editmsgrequest) returns (Editmsgreply) {} RPC Remove (removemsgrequest) Returns (Removemsgreply) {}}
The definition of the receive and return parameters corresponding to each of these methods is as follows:
View Code
So far we have completed the preparation of the agreement.
C. Making an agreement into C # code
Many tutorials about C # using GRPC are based on the. NET Project framework, so you can install Grpc.tools, but after the. NET core installation, you can't find the tool, so the reader can create a new one. NET project to install the class library and then copy the tools into Sino.GrpcService.Protocol , where the reader needs to choose according to your current system, and then create a new project named " Protocgenerate.cmd " file, where you enter the following command:
Protoc-i. --csharp_out. --grpc_out. --plugin=protoc-gen-grpc=grpc_csharp_plugin.exe Msg.proto
Then the reader directly double-click to run, you will see the project generated under the "Msg.cs" and "MsgGrpc.cs" two files, so that the completion of all the protocol part of the work, the final project structure is as follows:
D. Writing implementation code
With the protocol layer we can begin to write the implementation, because the author uses MongoDB to provide data, so the following space will be longer.
First open the Sino.GrpcService.Impl project in which you create a new model file, and then create a new MsgDM.cs file under that folder, which is primarily a data structure that defines the MongoDB store. The specific content is as follows:
View Code
Then we create a new repositories folder in which four new files are "IDataContext.cs", "DataContext.cs", "IMsgRepository.cs", and " MsgRepository.cs ". Open the IDataContext.cs file in which you wrote the following:
<summary>//database context/// </summary> public interface Idatacontext { Imongodatabase Database {get; set;} }
Open DataContext.cs file for database initialization related work:
public class Datacontext:idatacontext {public imongodatabase Database {get; set;} Public DataContext (iconfigurationroot config) { var client = new Mongoclient (config). GetConnectionString ("MongoDB")); Database = client. Getdatabase ("Asq0cwkeshl8nivn"); } }
Open IMsgRepository.cs, where we need to define the operations provided by the warehousing:
<summary>///News Warehousing/// </summary> public interface imsgrepository { //< summary> ///Get a list//</summary> task<list<msgdm>> GetList (Long userId, string Title, long startTime, long endTime); <summary> ///Get entity ///</summary> task<msgdm> get (string id); <summary> ///Update entity///</summary> task<bool> Update (MSGDM data); <summary> ///Add entities///</summary> task<string> Insert (MSGDM data); <summary> ///delete entity ///</summary> task<bool> Delete (string id); }
Corresponding we also need to open the MsgRepository.cs file to implement the interface:
View Code
Completed the above about the database work, the following we entered the topic, began to implement the GRPC service, first we create a new MsgServiceImpl.cs file under the project root directory, in which we implement the services in our agreement:
View Code
Third, certificate generation
A. Installing OpenSSL
First, readers need to download the OpenSSL installer from this website:
OpenSSL download
The author's system is WIN10 64 below is the "Win64 OpenSSL v1.1.0b".
B. Production of certificates
There are a lot of tutorials on the internet, but for the novice directly to the halo, some have CA, client and service have not, here I provide a comprehensive cmd script (the default CA is itself):
1 @echo off 2 set openssl_conf=c:\openssl-win64\bin\openssl.cfg 3 4 echo Generate CA key:5 OPENSSL genrsa-passout Pass : 1111-des3-out ca.key 4096 6 7 Echo Generate ca certificate:8 OpenSSL req-passin pass:1111-new-x509-days 365-key Ca.key-out ca.crt-subj "/c=cn/st=js/l=zj/o=sino/ou=test/cn=root" 9 echo Generate server key:11 OpenSSL Genrsa-passo UT pass:1111-des3-out server.key 409612 echo Generate server signing request:14 OpenSSL req-passin pass:1111-new-k EY server.key-out server.csr-subj "/c=cn/st=js/l=zj/o=sino/ou=test/cn=root" echo self-sign server certificate:17 O Penssl x509-req-passin pass:1111-days 365-in server.csr-ca ca.crt-cakey ca.key-set_serial 01-out server.crt18 E Cho Remove passphrase from server key:20 OpenSSL rsa-passin pass:1111-in server.key-out server.key21 echo Generate C Lient key23 OpenSSL genrsa-passout pass:1111-des3-out client.key 409624 echo Generate client signing request:26 Open SSL Req-passin pass:1111-new-key client.key-out client.csr-subj "/c=cn/st=js/l=zj/o=sino/ou=test/cn=root" Echo Self-sign client Certifi cate:29 OpenSSL x509-passin pass:1111-req-days 365-in client.csr-ca ca.crt-cakey ca.key-set_serial 01-out client.c Rt30 echo Remove passphrase from client key:32 OpenSSL rsa-passin pass:1111-in client.key-out Client.key
The above script will also generate the certificate we use in the demo below.
Four, perfect the service side
After using the above certificate we need to continue to start the service side of the GRPC Service section of the code to write, the author is run in command line form, so the GRPC start is independent in a file file, as shown in the following rpcconfiguration :
View Code
We used both the server.crt and server.key certificates, so we need to copy this two certificate file to the project root in the host project. If you need to publish the inclusion then you need to configure the following section in Project.json:
"Publishoptions": { "include": ["Server.crt", "Server.key", "Appsettings.json", "Appsettings.*.json"] }
Finally, we need to start the corresponding GRPC in program.
V. Client writing
The completion of the service side of the writing is the client's writing, of course, the client's writing is relatively easy, the author here directly to the Sino.GrpcService.Protocol The project is included in the client solution (the NuGet package is recommended for administration in formal development), so only one of the service interfaces is called for simplicity:
public static class Msgserviceclient {private static Channel _channel; private static msgservice.msgserviceclient _client; Static msgserviceclient () {var cacert = File.readalltext ("Server.crt"); var SSL = new Sslcredentials (CACert); var channoptions = new List<channeloption> {new Channeloption (Channeloptions.ssltargetnam Eoverride, "root")}; _channel = new Channel ("grpcservice.t0.daoapp.io:61130", SSL, Channoptions); _client = new Msgservice.msgserviceclient (_channel); public static getmsglistreply GetList (int userId, string title, Long StartTime, long EndTime) { Return _client. GetList (new Getmsglistrequest {userid = userid, title = title, St Arttime = startTime, EndTime = EndTime}); } }
It is necessary to note that the "channeloptions.ssltargetnameoverride" Part is required, because we are the certificates that we generate, so the domain name is root, and if it is a production environment, it is not required.
Vi. Running with Docker
A. Installing Docker for Windows
The WIN10 system is needed here, so you can directly use the Docker instructions directly in PS.
B. Writing Dockerfile
Because the 1.1 version came out, but after my verification, if your application does not upgrade is not able to use the image, the default use of 1.1, so here our dockerfile need to specify a specific version, otherwise it will not be built, We first create a new Dockerfile file in the root of the solution , and then put the following command in it:
1 from Microsoft/dotnet:1.0-sdk-projectjson 2 3 ADD.//USR/LOCAL/SRC 4 workdir/usr/local/src/ SINO.GRPCSERVICE.HOST/5 6 run CD/USR/LOCAL/SRC/7 run dotnet restore-v http://api.nuget.org/v3/index.json 8 Run Dot NET build 9 EXPOSE 900711 CMD ["dotnet", "Run"]
C. Build the image and run it
We open PS and then use the CD to the solution folder:
Docker build-t grpcservice:1.0.
Start building, based on the domestic situation, we recommend that you adjust the address of the Docker default pull mirror. After the build, use the following command to start:
Docker run-d–name-p 9007:9007 Grpcservice grpcservice:1.0
Of course, the address and port of the client connection should be adjusted according to the situation specified by-P.
Using GRPC Public Service (SSL/TLS) under. NET Core