In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
This article focuses on "how to use asp.net core+gRPC to achieve the migration of old WCF projects", interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Now let the editor take you to learn "how to use asp.net core+gRPC to achieve the migration of old WCF projects"!
A month ago, the company's windows server running WCF down dropped, and the problem could not be found immediately because AWS did not notify it.
Therefore, the customer proposes to change the WCF service from C# to JAVA and run on Linux; on the one hand, AWS has more monitoring measures for Linux, on the other hand, if there is a problem, you can set services such as automatic restart.
Old WCF service
At present, WCF service, which mainly provides the data interface of windows desktop software, should have a history of five or six years. Since I joined the company, the code of the WCF service has been maintained by me alone. There are many problems left over from history, and there are also different versions of the coexistence.
If java is rewritten, the business logic code will inevitably appear a variety of bug, increasing the workload of development and testing. I heard that after porting to linux services, the first thing that comes to mind is cross-platform. Net core.
Net core after four years of development, to the current version of 3.1 LST, has been a very mature cross-platform solution.
After that, I looked up on the Internet to see if there was a. Net core version of WCF. The information I got was summarized as follows:
Core WCF does not plan to do a 100% compatible migration from WCF to .NET Core
WCF, a SOAP technology, is not recommended for new applications
For older applications, it is recommended that you keep these on the .NET Framework
If you really want to migrate an old application to .NET Core and want to continue to use WCF and WF, community open source projects are also possible, but the production schedule is 2020. NET 5
The open source community is also strongly advised not to use it in a production environment at this time.
Unfortunately, it is almost impossible to migrate to Linux without changing the code.
In my best case, with as little handwritten code as possible, it would be better to automatically generate proxy classes, like WCF, to call the interface as if it were local code. Later, the form of asp.net core + gRPC was discovered.
Learn about gRPC
GRPC has many benefits: high performance, small data transmission, support for multi-language generation tools, the use of HTTP2 protocol, these benefits are described in detail on the Internet, this article will not repeat.
In fact, what I value most is that both client-side and server-side code can be generated automatically through an proto protocol file.
Microsoft officials also recommend using ASP.NET Core gRPC. "ASP.NET Core gRPC for WCF developers"
Proto file for gRPC
In order to understand the way proto documents are written, proto3 barely understands the general situation by looking at Google English documents. "Language Guide (proto3)", here are some summaries of my experience in using it:
A RPC service must have one and only one input parameter and one output parameter; if not, it can be set to an empty object google.protobuf.Empty
Basic types (string, int32, etc.) cannot be used as parameters for PRC services. You can use the encapsulated objects provided by Google, such as google.protobuf.StringValue,google.protobuf.Int32Value, see the google/protobuf/wrappers.proto file for details.
Proto3 does not allow null values, because Protobuf binary serialization, null and null can not be distinguished, using google.protobuf.StringValue can achieve null values; same as point 2
The number string name=1; must be written and used for Protobuf binary serialization, and the commonly used attributes had better be put in the first 12 of them. PS: too unaccustomed, always thinking that they are assigning values
Enumerated types must start at 0, that is, enum Weekday {Sunday=0;Monday=2;}
Time type google.protobuf.Timestamp, must be UTC time
Message body message cannot be inherited, can be nested in multiple layers, and can be imported into import
/ / my example
Syntax = "proto3"
Option csharp_namespace = "GrpcServiceTest.Protos"
Import "Protos/ClientInfoModel.proto"
Import "google/protobuf/timestamp.proto"
Import "google/protobuf/wrappers.proto"
Package UserManagement
Service UserManagement {
Rpc UserReset (google.protobuf.Empty) returns (google.protobuf.Empty)
Rpc UserLogin (LoginRequestV2) returns (LoginResponseV2)
}
Message LoginRequestV2 {
String UserName = 1
String Password = 2
}
Message LoginResponseV2 {
Int32 TAG = 1
String Message = 2
UserModelV2 UserInfo = 3
Message UserModelV2 {
Int64 UserID = 1
String UserName = 2
Google.protobuf.StringValue Address = 3
Google.protobuf.Timestamp LastLoginTime = 4
Repeated PrivGroupPluginModelV2 PrivGroupPlugins = 5
Bool IsDeleted = 6
Message PrivGroupPluginModelV2 {
Int64 Id=1
Google.protobuf.Timestamp CreateDateTime=2
Google.protobuf.Timestamp ModifyDateTime=3
Int64 PluginId=4
Int64 PrivGroupPluginID=5
}
}
}
Generate code according to proto
With vs2019, select the gRPC Service project template to create the project. It automatically adds the nuget package Grpc.AspNetCore. If not, you need to install the nuget package yourself: Grpc.core, Google.Protobuf, Grpc.Tools.
There are two ways to generate code from a proto file:
Right-click the proto file through vs, select property Property, select Protobuf complier in Build Action, and you will see gRPC Stub Classes. There are three options: Server Only, Clent Only and Both on demand.
Edit the project file csproj, edit Protobuf properties, this method can also use path macros, wildcards, etc., quite convenient, highly recommended.
Asp.net core 3.1
Now, just in time for the release of the LST version (long-term-support) of net core 3.1, the life cycle of NET Core 3.0 ends on March 3, 2020, and the next unified version of NET 5, the official version, will not be available until next year. As to why there is no NET version 4.0, the official explanation is to avoid ambiguity in .NET Framework 4.X.
Follow the guidelines of the official documents step by step and follow them. "gRPC Services using ASP.NET Core", "tutorial: creating gRPC clients and servers in ASP.NET Core"
In retrospect, there is really nothing worth saying in this part, and the official documents are already very detailed. The only difference is that if net core needs anything, it needs to be installed through nuget, which is very different from net framework. Framework is more like helping you install it all at once.
Entity Framework Core
In the old WCF project, database access used Entity Framework + Linq + MySql. Nuget packages that need to be installed:
MySql.Data.EntityFrameworkCore Mysql's EF Core Library
Microsoft.EntityFrameworkCore.Proxies "Lazy loading" lazy loaded plug-ins
Microsoft.EntityFrameworkCore.Design and Microsoft.EntityFrameworkCore.Tools, two plug-ins for generating code
In addition, you need to download and install mysql-connector-net-8.0.21.msi to access the database. One of the Scaffold-DbContext 's bug 99419 TINYINT (1) is converted to byte instead of the expected bool. This issue will be fixed in version 8.0.22 and can only be fixed manually.
EF is Database First, of course. To generate EF code, you need to use the Scaffold-DbContext command in Package Manager Console. There are three points to note:
The Start up startup project must refer to its project and compile successfully
The project where the code is stored after the Default project is generated
If the build fails, prompt: "Your startup project 'XXXX' doesn't reference Microsoft.EntityFrameworkCore.Design. This package is required for the EntityFrameworkCore Tools to work. Ensure your startup project is correct, install the package, and try again." Edit the project file csproj to remove All from "Microsoft.EntityFrameworkCore.Design" and "Microsoft.EntityFrameworkCore.Tools"
My command: Scaffold-DbContext-Connection "server=10.50.40.50;port=3306;user=myuser;password=123456;database=dbname"-Provider MySql.Data.EntityFrameworkCore-OutputDir "EFModel"-ContextDir "Context"-Project "DataAccess"-Context "BaseEntities"-UseDatabaseNames-Force
Other suggestions:
Library class library is preferably netstandard for easy portability.
Create a new class to inherit BaseEntities, override OnConfiguring method, configurable database connection string
Public class Entities: BaseEntities
{
Private static string _ lstDBString
Public static void SetDefaultDBString (string _ dbString)
{
If (string.IsNullOrEmpty (_ lstDBString))
{
_ lstDBString = _ dbString
}
}
Protected override void OnConfiguring (DbContextOptionsBuilder optionsBuilder)
{
If (! optionsBuilder.IsConfigured)
{
OptionsBuilder.UseLazyLoadingProxies () .UseMySQL (_ lstDBString)
}
}
}
It is best to use asp.net core framework injection; in view of the reasons of the project, if forced to adopt, the change is relatively large, have no choice but to give up
Public void ConfigureServices (IServiceCollection services)
{
String _ dbString = Configuration.GetConnectionString ("LstDatabase")
Services.AddDbContext (
Options = > options.UseLazyLoadingProxies () .UseMySQL (_ dbString))
Services.AddGrpc ()
}
Database link strings can be stored in a variety of ways and in a more secure way, while I use a simple way to store them in appsettings.json
{
"ConnectionStrings": {
"LstDatabase": "server=127.0.0.1;port=3306;user=myuser;password=123456;database=dbname"
}
"log4net": "log4net.config"
"Logging": {
"LogLevel": {
"Default": "Information"
"Microsoft": "Warning"
"Microsoft.Hosting.Lifetime": "Information"
}
}
AllowedHosts: "*"
}
Deploy to Ubuntu
The server running in the production environment is Ubuntu 14.04.6 LTS, which is described on "ubuntu Releases wiki". Version 14 stopped standard support last year, and the minimum runtime support for .net core is Ubuntu 16.04.6 LTS, so we have to choose the latest version, Ubuntu 20.04.1 LTS.
Installation of Ubuntu Server system episode: colleagues in IT support department helped to reinstall the system twice, once 14.04desktop version and 20.04server version; after installing version 20, I found that the network card was not enabled and the lights on the network cable behind the host were not on.
Since he and I are not familiar with the Ubuntu system, we look up the method on the Internet, then use our mobile phone to take pictures, and then try it on the server. It took us a while to connect to the network, but SSH was not enabled. Maybe Ubuntu is more suitable for desktop systems.
Then refer to "installing .NET Core SDK or .NET Core Runtime on Ubuntu" to install netcore in an environment that initially uses aspnetcore-runtime, and during testing, you find that gRPC requires HTTPS. HTTPS, which has been tossing around for a long time, needs to sign for a while, generate a key for a while, and put it at a specified location for a while, and also need to toss about trusted certificates. After tossing about for a long time, the skull was a mass of paste. I had to install dotnet-sdk again, which is a self-contained development certificate. Anyway, I will just use it.
The rest is relatively simple, compile and publish the asp.net core, package and upload it to the server, and then run dotnet GrpcServiceLST.dll-- urls "http://*:5000;http://*:5001". Open the browser to test the access, there is no problem.
The writing of client
When writing windows clients, there is a problem: the plug-in Grpc.Net.ClientFactory recommended by "gRPC client Factory Integration in .NET Core" can only be applied to net core, while most customers' windows7 systems do not install net core;. If you want to use gRPC on net framework, you can only implement it natively.
The method of generating code using the proto file is the same as above, only by changing Server Only to Client Only; note in the code section that the deployed HTTPS is untrusted and requires additional processing.
/ net core 3.1
Private void button2_Click (object sender, EventArgs e)
{
/ / cancel untrusted
Var httpHandler = new HttpClientHandler ()
HttpHandler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
Var channel = GrpcChannel.ForAddress ("https://10.50.40.237:5001", new GrpcChannelOptions {HttpHandler = httpHandler})
Var client = new UserManagement.UserManagementClient (channel)
Var _ param = new GrpcServiceLST.Protos.LoginRequestV2 ()
{
UserName = "user"
Password = "123456"
}
Var reply = client.UserLoginOSDShadowEx (_ param)
MessageBox.Show ("net core login:" + reply.Message)
}
/ framework 4.0
Private void button1_Click (object sender, EventArgs e)
{
Var channel = new Channel ("10.50.40.237 var channel 5000", ChannelCredentials.Insecure)
Var client = new UserManagement.UserManagementClient (channel)
Var _ param = new GrpcServiceLST.Protos.LoginRequestV2 ()
{
UserName = "user"
Password = "123456"
}
Var _ reply = client.UserLoginOSDShadowEx (_ param)
MessageBox.Show ("framework login:" + _ reply.Message)
}
After testing, it is found that net core's gRPC desktop program does not support http access; net framework desktop programs use the native version of gRPC and can only access http port 5000, but not https port 5001, and cannot use prefixes such as http or https (for example, domain names such as http://10.50.40.237:5000) Magazine localhost cannot be resolved.
HTTPHTTPS domain name IPnet core gRPC client x √√√ framework gRPC client √ xx √
The most fatal thing is that when net core is installed on a win7 system, it is unexpectedly inaccessible with Grpc.Net.ClientFactory. The answer is found on github, win7 will not support http2, and win7 Microsoft stopped providing support on January 14, 2020.
Issues: ASP.NET Core uses the operating system for HTTP/2 TLS support. MacOS may support hosting servers with HTTP/2 TLS in the future, Windows 7 will not.
At this point, I believe you have a deeper understanding of "how to use asp.net core+gRPC to achieve the migration of old WCF projects". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.