search
HomeBackend DevelopmentC#.Net TutorialIntroduction to several service frameworks under .NET

Introduction


#After the company has more services, for the convenience of calling and for future service management, some service frameworks are generally used. Here are the main introductions I know several service frameworks. Let me briefly analyze the basic concepts of these service frameworks.


Can be put into production environment


I have seen companies invest in the following two service frameworks It is a production environment, so there should be no need to worry too much about stability.

ServiceStack https://github.com/ServiceStack/ServiceStack


ServiceStack may not have been used, but its other two A component, everyone should have used it, ServiceStack.Redis (Redis access tool), ServiceStack.Text (Json serialization tool), ServiceStack is a service framework, you can easily use it to create services, the service is based on http, In addition, client calls are provided. The data serialization methods include Json, xml, binary, and Protobuf, and the created services have certain descriptions.


1 http request, there are two key things, the request path and parameters. For ServiceStack, the parameters are objects, that is, the parameters it wants to pass are encapsulated into a class Inside, add a label to the class, and the content of the label is the request path, so that when the client calls, it will reflect the request path and parameters, and then initiate the call.


Because ServiceStack itself has provided a demo, I won’t write a demo here. You can learn about it.

Hessian https://sourceforge.net/projects/hessiancsharp/


Hessian is a serialization tool and also a The service framework provides implementation in multiple languages, including .net. This component seems not very famous in the .Net field, and it may not have been updated for a long time.

When using Hessian, you first need to define the interface, and then make two copies. The server implements these interfaces. The client references these interfaces, and then the client uses the RealProxxy class as a proxy. All interface calls will eventually be called In the Invoke method in the proxy class, the name of the method to be called, parameters and other contents are obtained in the Invoke method, and are serialized and sent to a unified URL on the server. This URL will end with hessian, so it needs to be in web.config Configure a handle to intercept the request. After intercepting the request, deserialize the parameters and then initiate the call through reflection.


You can refer to this blog for calling here http://www.cnblogs.com/lxsfg/archive/2008/08/27/1277777.html

There are many other service frameworks, such as thrift and JSON-RPC, but since I have not used them before, I will not comment here.


Some service frameworks in the blog park

The following three frameworks were discovered when I browsed the blog park, and they are all open source. For Learning the service framework is a good project. In addition, I don’t often go to the blog park. The following three frameworks were also seen by chance. There should be other excellent service frameworks in the blog park, but I haven’t discovered them. If you find them, you might as well Write in the comment area and let’s learn together.

Rabbit.Rpc http://www.cnblogs.com/ants/p/5605754.html

is somewhat similar to Hessin. It also defines the service interface first. Then in duplicate, the server implements specific logic by inheriting the interface. For the client, it extracts all methods in the interface, as well as method parameters and return value information through reflection, and then dynamically generates code to generate A proxy class is dynamically compiled and put into the container. Regarding the generated proxy class, all methods have a unified implementation, that is, calling an Invoke method to send the methods and parameters to the bottom layer, and the bottom layer assembly is sent to the server. The way to generate code here is more fun, you can learn it.


In addition, this framework also integrates service management. The service is registered to Zookeeper, and the client gets the specific service address through Zookeeper to call. In fact, at this point, this is not just a service framework, but also includes service governance functions.


# I only read the code briefly, and I haven’t fully understood the details yet. If you want to know more about it, you can read the source code.

Dyd.BaseService.ServiceCenter http://git.oschina.net/chejiangyi/Dyd.BaseService.ServiceCenter

Look at the basic introduction All functions are available, but according to the author's introduction to this project, it is said that this project is research-oriented, and the client for service calls is also generated through code. For details, please refer to the code.

In addition, let me introduce this blogger more. He also has a blog in the blog park http://www.cnblogs.com/chejiangyi/, and has opened several open source projects http ://git.oschina.net/chejiangyi These are some very good projects, such as scheduling services, configuration services, and monitoring services. For Internet companies of a certain scale, these services are needed, and what is more valuable is that these services are It is based on .Net, so it has good reference significance for some Internet companies that use .Net development.

Redola.Rpc http://www.cnblogs.com/gaochundong/p/redola_yet_another_csharp_rpc_framework.html

This is what I discovered recently. The framework uses the Actor model and serialization uses protobuf-net, the transmission method is based on tcp, and the tcp framework uses its own Cowboy.WebSockets. According to the introduction, the service center is also implemented, but because I don’t understand the Actor model, I won’t add anything here. Interested students You can read the author's blog.


The service framework I wrote myself

After reading so many service frameworks, I also wrote one myself. It is just a service call and It is experimental in nature and can be used as a reference.

The principle of the framework is similar to that of Hession. The interface must be defined first, and then the server implements the interface. Here I took a trick. I directly let the Controller in the Web API inherit the interface, so there is no need to specifically define one. Handle is used to intercept requests without affecting Web Api access, so even if you use this framework, it will not prevent you from accessing directly via http. The calling method of the client is similar to Hession. It also needs to define a proxy and then collect parameters.

First define the interface

Introduction to several service frameworks under .NETWith the interface, the next step is to implement it. Here I am using Web API. We define a Controller. In addition to inheriting APIController, this Controller also inherits the interface. In this Controller, the specific logic of the interface is implemented.

Introduction to several service frameworks under .NETAt the same time, copy the dll where this interface is located to the client. Here we will introduce a function, which is RealProxy. This is the proxy class that comes with .Net and is also used by Hession. Mechanisms.

using System;
using System.Linq;
using System.Reflection;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Remoting.Proxies;
using Newtonsoft.Json;
using RestSharp;
namespace SimleRPC
{
    public class SimpleProxy : RealProxy
    {
        private readonly Uri _uri;
        public SimpleProxy(Type type, Uri uri) : base(type)
        {
            this._uri = uri;
        }
        public override IMessage Invoke(IMessage msg)
        {
            //msg参数包含调用方法的信息,这里通过封装,使信息更丰富一些
            IMethodCallMessage methodMessage = new MethodCallMessageWrapper((IMethodCallMessage)msg);
            MethodInfo methodInfo = (MethodInfo)methodMessage.MethodBase;
            ParameterInfo[] paramsInfo = methodInfo.GetParameters();  //获取方法调用参数
            //拼装path  类名即controller名, 方法名即action名  这样就表示出具体的url
            string path = "/api/" + methodInfo.DeclaringType.Name + "/" + methodInfo.Name;
            //请求类型,post or get
            bool isHttpGet = methodInfo.CustomAttributes.Any(customAttributeData => customAttributeData.AttributeType.Name == "HttpGetAttribute");
            var client = new RestClient(_uri);
            var request = new RestRequest(path, isHttpGet ? Method.GET : Method.POST);
            //构建参数
            //web api对于传参的一切规则  参考 http://www.cnblogs.com/babycool/p/3922738.html    http://www.cnblogs.com/landeanfen/p/5337072.html 两篇博客
            if (isHttpGet)
            {
                //这里默认get请求的参数都是基本类型
                for (int i = 0; i < paramsInfo.Length; i++)
                {
                    request.AddParameter(paramsInfo[i].Name, methodMessage.Args[i]);
                }
            }
            else
            {
                //对于post请求,要么没有参数(当然基本没有这种情况),要么只有一个参数(这些是受web api的限制)
                if (paramsInfo.Length > 0)
                {
                    request.AddJsonBody(methodMessage.Args[0]);
                }
            }
            // 发送请求 拿到结果
            IRestResponse response = client.Execute(request);
            var content = response.Content;
            Type returnType = methodInfo.ReturnType;     //获取调用方法返回类型,根据类型反序列化结果
            object returnValue;
            if (IsBaseType(returnType))
            {
                returnValue = Convert.ChangeType(content, returnType);
            }
            else
            {
                returnValue = JsonConvert.DeserializeObject(content, returnType); //如果是一个对象,则用json进行反序列化
            }
            return new ReturnMessage(returnValue, methodMessage.Args, methodMessage.ArgCount, methodMessage.LogicalCallContext, methodMessage);
        }
        /// <summary>
        /// 判断是否是基础类型(int long  double), string 是引用类型,但是也归到基础类型里面
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        private static bool IsBaseType(Type type)
        {
            if (type == typeof(string) || type.IsPrimitive)
                return true;
            return false;
        }
    }
}

All method calls will call the Invoke method. In the Invoke method, you can get the specific information of the calling method, such as parameters, return value type, etc. Then through reflection and assembly, an Http request is formed. Here, my default interface class name is the name of the Controller, and the interface method name is the name of the Action.

Finally, send the request through RestSharp. Finally, the http result is deserialized into the value required for the method return value.

Introduction to several service frameworks under .NETIn fact, for the server, it doesn’t matter whether the Web API inherits the interface. If it does not, the signature of the interface must be consistent with the signature of the method in the Web API. .

The method can be adjusted through the Demo I wrote. If anyone is interested in this, you can test some more situations.


at last

Many Internet companies now have their own RPC frameworks, some of which are open source, and some of which are written by themselves due to historical issues. As for communication methods, there are some based on HTTP, some based on TCP, and both protocols. compatible. There are also various serialization methods. I only listed 5 above. In fact, searching on github, there are many excellent RPCs.


RPC is only a stage in the project development process. With RPC, you can do a lot of things on this basis, such as:


Service governance All services are registered to the service center when they are started, and the client is started When getting the real address from the registration center, call it directly without going through a proxy such as Nginx. Here you can put some permission restrictions on getting the real address, such as which clients can be used, which clients cannot be used, and how many can be used. You can refer to dubbo here.


Http request path Microservices are very popular now. A front-end request may go through several back-end services. You can add RequestId and RequestIndex to the http header. Services are strung together, for example A->B->C. When service A calls service B, if it is found that there is no RequestId in the http head, one can be generated through GuId, and the RequestIndex is increased by 1. When service B calls server C, , because the RequestId already exists, it is passed directly, and the RequestIndex is increased by 1, and the information is recorded in the log. Through analysis, the entire call is strung together, and the call link diagram of the entire service can be drawn through the complete data. .


In addition to the link diagram, because we can intercept each service call, we can record the service call time, plus the link diagram, the entire service The information will be more complete.

The above is the introduction of several service frameworks under .NET. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Mastering C# .NET Design Patterns: From Singleton to Dependency InjectionMastering C# .NET Design Patterns: From Singleton to Dependency InjectionMay 09, 2025 am 12:15 AM

Design patterns in C#.NET include Singleton patterns and dependency injection. 1.Singleton mode ensures that there is only one instance of the class, which is suitable for scenarios where global access points are required, but attention should be paid to thread safety and abuse issues. 2. Dependency injection improves code flexibility and testability by injecting dependencies. It is often used for constructor injection, but it is necessary to avoid excessive use to increase complexity.

C# .NET in the Modern World: Applications and IndustriesC# .NET in the Modern World: Applications and IndustriesMay 08, 2025 am 12:08 AM

C#.NET is widely used in the modern world in the fields of game development, financial services, the Internet of Things and cloud computing. 1) In game development, use C# to program through the Unity engine. 2) In the field of financial services, C#.NET is used to develop high-performance trading systems and data analysis tools. 3) In terms of IoT and cloud computing, C#.NET provides support through Azure services to develop device control logic and data processing.

C# .NET Framework vs. .NET Core/5/6: What's the Difference?C# .NET Framework vs. .NET Core/5/6: What's the Difference?May 07, 2025 am 12:06 AM

.NETFrameworkisWindows-centric,while.NETCore/5/6supportscross-platformdevelopment.1).NETFramework,since2002,isidealforWindowsapplicationsbutlimitedincross-platformcapabilities.2).NETCore,from2016,anditsevolutions(.NET5/6)offerbetterperformance,cross-

The Community of C# .NET Developers: Resources and SupportThe Community of C# .NET Developers: Resources and SupportMay 06, 2025 am 12:11 AM

The C#.NET developer community provides rich resources and support, including: 1. Microsoft's official documents, 2. Community forums such as StackOverflow and Reddit, and 3. Open source projects on GitHub. These resources help developers improve their programming skills from basic learning to advanced applications.

The C# .NET Advantage: Features, Benefits, and Use CasesThe C# .NET Advantage: Features, Benefits, and Use CasesMay 05, 2025 am 12:01 AM

The advantages of C#.NET include: 1) Language features, such as asynchronous programming simplifies development; 2) Performance and reliability, improving efficiency through JIT compilation and garbage collection mechanisms; 3) Cross-platform support, .NETCore expands application scenarios; 4) A wide range of practical applications, with outstanding performance from the Web to desktop and game development.

Is C# Always Associated with .NET? Exploring AlternativesIs C# Always Associated with .NET? Exploring AlternativesMay 04, 2025 am 12:06 AM

C# is not always tied to .NET. 1) C# can run in the Mono runtime environment and is suitable for Linux and macOS. 2) In the Unity game engine, C# is used for scripting and does not rely on the .NET framework. 3) C# can also be used for embedded system development, such as .NETMicroFramework.

The .NET Ecosystem: C#'s Role and BeyondThe .NET Ecosystem: C#'s Role and BeyondMay 03, 2025 am 12:04 AM

C# plays a core role in the .NET ecosystem and is the preferred language for developers. 1) C# provides efficient and easy-to-use programming methods, combining the advantages of C, C and Java. 2) Execute through .NET runtime (CLR) to ensure efficient cross-platform operation. 3) C# supports basic to advanced usage, such as LINQ and asynchronous programming. 4) Optimization and best practices include using StringBuilder and asynchronous programming to improve performance and maintainability.

C# as a .NET Language: The Foundation of the EcosystemC# as a .NET Language: The Foundation of the EcosystemMay 02, 2025 am 12:01 AM

C# is a programming language released by Microsoft in 2000, aiming to combine the power of C and the simplicity of Java. 1.C# is a type-safe, object-oriented programming language that supports encapsulation, inheritance and polymorphism. 2. The compilation process of C# converts the code into an intermediate language (IL), and then compiles it into machine code execution in the .NET runtime environment (CLR). 3. The basic usage of C# includes variable declarations, control flows and function definitions, while advanced usages cover asynchronous programming, LINQ and delegates, etc. 4. Common errors include type mismatch and null reference exceptions, which can be debugged through debugger, exception handling and logging. 5. Performance optimization suggestions include the use of LINQ, asynchronous programming, and improving code readability.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft