Home >Backend Development >C#.Net Tutorial >Introduction 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
With 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.
At 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.
In 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)!