In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >
Share
Shulou(Shulou.com)05/31 Report--
Today I will show you what the RPC framework DotNetCoreRpc based on. NetCore looks like. The content of the article is good. Now I would like to share it with you. Friends who feel in need can understand it. I hope it will be helpful to you. Let's read it along with the editor's ideas.
Preface
It has always been in favor of using RPC between internal services, because there are not so many internal restrictions, and the simplest and most straightforward way is the most appropriate way. Individuals prefer the kind of use similar to Dubbo, using the same way as the local method, separate the interface layer as a service contract to provide services for the server, and the client also invokes the service through this contract. Net platform such a relatively perfect RPC framework such as Dubbo is still relatively few, GRPC is indeed a very good RPC framework, can be cross-language calls, but every time you have to write proto files, personal feeling is more troublesome. Nowadays, under the trend of service split and micro-service architecture, a simple and practical RPC framework can indeed improve a lot of development efficiency.
Brief introduction
As the .net Core matured and stabilized, it provided a convenient way for me to achieve this goal. So I handwritten a set of RPC framework based on Asp.Net Core in my spare time, which can be regarded as achieving a small goal of my own. Generally speaking, the server side relies on Asp.Net Core, and it is convenient to intercept and process requests in the way of middleware. The Client side can be any host program that can host .net Core. The mode of communication is HTTP protocol and HttpClientFactory is used. As for why to use HttpClientFactory, because HttpClientFactory can more easily achieve service discovery, and can be well integrated with Polly, very convenient implementation, timeout retry, circuit breaker downgrade these, to provide a lot of convenience in the development process. Due to my limited ability, based on these conveniences, standing on the shoulder of the giant, I simply implemented a RPC framework, and the project is hosted on GitHub. Https://github.com/softlgl/DotNetCoreRpc who is interested can consult it on their own.
Development environment
Visual Studio 2019
.Net Standard 2.1
Asp.Net Core 3.1.x
Mode of use
Open Visual Studio and create a new RPC contract interface layer. Here my name is IRpcService. Then create a new Client layer (which can be any host program that can host .net Core) called ClientDemo, and then establish a Server layer (which must be an Asp.Net Core project) called WebDemo. The Demo connection of this article is attached at the end of the article. After this, the project structure is as follows:
Client side configuration #
The Client side introduces DotNetCoreRpc.Client package and a custom contract interface layer.
Then you can code happily, roughly as follows
Class Program {static void Main (string [] args) {IServiceCollection services = new ServiceCollection (); / / * Registration of DotNetCoreRpcClient core service services.AddDotNetCoreRpcClient () / / * Communication is based on HTTP. HttpClientFactory for internal use can be registered by yourself. AddHttpClient ("WebDemo", client = > {client.BaseAddress = new Uri ("http://localhost:13285/");}); IServiceProvider serviceProvider = services.BuildServiceProvider ()) / / * get RpcClient to create a specific service proxy object RpcClient rpcClient = serviceProvider.GetRequiredService () using this class; / / IPersonService is the service pack interface I introduced, and you need to provide ServiceName, that is, the name of AddHttpClient IPersonService personService = rpcClient.CreateClient ("WebDemo") PersonDto personDto = new PersonDto {Id = 1, Name = "between yi readings", Address = "China", BirthDay = new DateTime (2000), IsMarried = true, Tel = 88888888888}; bool addFlag = personService.Add (personDto); Console.WriteLine ($"add result = [{addFlag}]") Var person = personService.Get (personDto.Id); Console.WriteLine ($"get person result = [{person.ToJson ()}]"); var persons = personService.GetAll (); Console.WriteLine ($"get persons result = [{persons.ToList (). ToJson ()}]"); personService.Delete (person.Id); Console.WriteLine ($"deletion complete"); Console.ReadLine () }}
At this point, the code on the client side is finished.
Server side configuration #
The Client side introduces DotNetCoreRpc.Client package and a custom contract interface layer.
Then write the contract interface implementation class, such as mine called PersonService
/ / implement contract interface IPersonServicepublic class PersonService:IPersonService {private readonly ConcurrentDictionary persons = new ConcurrentDictionary (); public bool Add (PersonDto person) {return persons.TryAdd (person.Id, person);} public void Delete (int id) {persons.Remove (id,out PersonDto person);} / / Custom Filter [CacheFilter (CacheTime = 500)] public PersonDto Get (int id) {return persons.GetValueOrDefault (id) } / / Custom Filter [CacheFilter (CacheTime = 300)] public IEnumerable GetAll () {foreach (var item in persons) {yield return item.Value;}
As you can see from the above code, I have customized the Filter. The Filter here is not the Filter defined by the Asp.Net Core framework, but the Filter defined by the DotNetCoreRpc framework. The way to customize the Filter is as follows
/ / * to inherit from abstract class RpcFilterAttributepublic class CacheFilterAttribute: RpcFilterAttribute {public int CacheTime {get; set;} / / * supports attribute injection, which can be public or private / / * where the FromServices is not under the Asp.Net Core namespace, but from the DotNetCoreRpc.Core namespace [FromServices] private RedisConfigOptions RedisConfig {get; set;} [FromServices] public ILogger Logger {get; set } public override async Task InvokeAsync (RpcContext context, RpcRequestDelegate next) {Logger.LogInformation ($"CacheFilterAttribute Begin,CacheTime= [{CacheTime}], Class= [{context.TargetType.FullName}], Method= [{context.Method.Name}], Params= [{JsonConvert.SerializeObject (context.Parameters)}]"); await next (context); Logger.LogInformation ($"CacheFilterAttribute End,ReturnValue= [{JsonConvert.SerializeObject (context.ReturnValue)}]");}}
The above code basically completes the operation of the server-side business code, so let's look at how to configure the use of DotNetCoreRpc in Asp.Net Core. Open Startup and configure the following code
Public class Startup {public void ConfigureServices (IServiceCollection services) {services.AddSingleton () .AddSingleton (new RedisConfigOptions {Address = "127.0.0.1 IServiceCollection services 6379" Db = 10}) / / * Register DotNetCoreRpcServer .AddDotNetCoreRpcServer (options = > {/ / * ensure that the added contract service interface has been registered in advance in the DI container / / add contract interface / / options.AddService () / / or add / / options.AddService ("* Service") with the contract interface name ending with xxx; / / or add the contract interface / / options.AddService ("IPersonService") with the specific name xxx; / / or scan the contract interface options.AddNameSpace ("IRpcService") under the specific namespace / / you can add a global filter in the same way as CacheFilterAttribute options.AddFilter ();} public void Configure (IApplicationBuilder app, IWebHostEnvironment env) {/ / this heap can not be + 1 if (env.IsDevelopment ()) {app.UseDeveloperExceptionPage () } / / add DotNetCoreRpc middleware either app.UseDotNetCoreRpc (); / / not + 2 app.UseRouting () in this heap; / / not + 3 app.UseEndpoints in this heap (endpoints = > {endpoints.MapGet ("/", async context = > {await context.Response.WriteAsync ("Server Start!")) });});}} what is the relevant content of DotNetCoreRpc? you can search the previous articles or browse the following articles to learn! I believe the editor will add more knowledge to you. I hope you can support it!
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.