大比速:remoting、WCF(http)、WCF(tcp)、WCF(RESTful)、asp.net core(RESTful)

近来在考虑一个服务选型,dotnet提供了众多的远程服务形式。在只考虑dotnet到dotnet的情形下,我们可以选择remoting、WCF(http)、WCF(tcp)、WCF(RESTful)、asp.net core(RESTful)
其中我考察的重点是前4项的效率差异,而在我的测试项目中他们共用同一个接口定义

[ServiceContract]
public interface ICalc
{
    [OperationContract]
    [WebInvoke(Method = "POST",
            RequestFormat = WebMessageFormat.Json,
            ResponseFormat = WebMessageFormat.Json,
            BodyStyle = WebMessageBodyStyle.Bare,
            UriTemplate = "cmd")]
    CalcInfo Calc(CalcInfo pInfo);
}

先来对比传入较为简单的CalcInfo,该类的json只有如下,其中集合Items是空的

{
    "id": 0,
    "method": "test",
    "para1": 0,
    "para2": 0,
    "result": 999,
    "items": []
}

测试从客户端将一个CalcInfo的实例传入服务端,服务端稍加修改Method返回给客户端的过程,主要测试序列化与传输的用时。记录执行10000次请求的总用时

Remoting用时 3.76s
WCF(http) 用时 21.92s
WCF(tcp)用时 5.96s
WCF(RESTful)用时 2.26s
asp.net Core(RESTfull)用时 16.59s

再来一下比较传输一个较大的CalcInfo,该类的json如下,其中items集合有100个子实例

{
    "id": 0,
    "method": "test",
    "para1": 0,
    "para2": 0,
    "result": 999,
    "items": [
        {
            "name": "test 1",
            "para1": 1,
            "para2": 0
        },
        {
            "name": "test 2",
            "para1": 2,
            "para2": 0
        }
//....共有100个子项
    ]
}

Remoting用时 12.94s
WCF(http) 用时  47.38s
WCF(tcp)用时 9.2s
WCF(RESTful)用时 10.67s
asp.net Core(RESTfull)用时 26.08s

把两个时间放在一起对比一下就很有意思了。小流量时remoting比WCF强,WCF(TCP)莫名的高用时,比json的还要高。在大流量的时候WCF的优势体现出来了,基本符合网上大致的观点。其中WCF(RESTful)让kevin-y印象深刻,几乎与TCP一样的成绩

小流量

Remoting用时 3.76s
WCF(http) 用时 21.92s
WCF(tcp)用时 5.96s
WCF(RESTful)用时 2.26s
asp.net Core(RESTfull)用时 16.59s

大流量

Remoting用时 12.94s
WCF(http) 用时  47.38s
WCF(tcp)用时 9.2s
WCF(RESTful)用时 10.67s
asp.net Core(RESTfull)用时 26.83s

测试的源代码来这
https://files.cnblogs.com/files/kevin-Y/SrvSpeed2.zip

 
 
 

.net core 控制台程序使用依赖注入(Autofac)

 

1、Autofac IOC 容器 ,便于在其他类获取注入的对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Autofac;
using Autofac.Core;
using Autofac.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
 
namespace BackToCOS.IoC
{
    /// <summary>
    /// Autofac IOC 容器
    /// </summary>
    public class AutofacContainer
    {
        private static ContainerBuilder _builder = new ContainerBuilder();
        private static IContainer _container;
        private static string[] _otherAssembly;
        private static List<Type> _types = new List<Type>();
        private static Dictionary<Type, Type> _dicTypes = new Dictionary<Type, Type>();
 
        /// <summary>
        /// 注册程序集
        /// </summary>
        /// <param name="assemblies">程序集名称的集合</param>
        public static void Register(params string[] assemblies)
        {
            _otherAssembly = assemblies;
        }
 
        /// <summary>
        /// 注册类型
        /// </summary>
        /// <param name="types"></param>
        public static void Register(params Type[] types)
        {
            _types.AddRange(types.ToList());
        }
        /// <summary>
        /// 注册程序集。
        /// </summary>
        /// <param name="implementationAssemblyName"></param>
        /// <param name="interfaceAssemblyName"></param>
        public static void Register(string implementationAssemblyName, string interfaceAssemblyName)
        {
            var implementationAssembly = Assembly.Load(implementationAssemblyName);
            var interfaceAssembly = Assembly.Load(interfaceAssemblyName);
            var implementationTypes =
                implementationAssembly.DefinedTypes.Where(t =>
                    t.IsClass && !t.IsAbstract && !t.IsGenericType && !t.IsNested);
            foreach (var type in implementationTypes)
            {
                var interfaceTypeName = interfaceAssemblyName + ".I" + type.Name;
                var interfaceType = interfaceAssembly.GetType(interfaceTypeName);
                if (interfaceType.IsAssignableFrom(type))
                {
                    _dicTypes.Add(interfaceType, type);
                }
            }
        }
        /// <summary>
        /// 注册
        /// </summary>
        /// <typeparam name="TInterface"></typeparam>
        /// <typeparam name="TImplementation"></typeparam>
        public static void Register<TInterface, TImplementation>() where TImplementation : TInterface
        {
            _dicTypes.Add(typeof(TInterface), typeof(TImplementation));
        }
 
        /// <summary>
        /// 注册一个单例实体
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="instance"></param>
        public static void Register<T>(T instance) where T:class
        {
            _builder.RegisterInstance(instance).SingleInstance();
        }
 
        /// <summary>
        /// 构建IOC容器
        /// </summary>
        public static IServiceProvider Build(IServiceCollection services)
        {
            if (_otherAssembly != null)
            {
                foreach (var item in _otherAssembly)
                {
                    _builder.RegisterAssemblyTypes(Assembly.Load(item));
                }
            }
 
            if (_types != null)
            {
                foreach (var type in _types)
                {
                    _builder.RegisterType(type);
                }
            }
 
            if (_dicTypes != null)
            {
                foreach (var dicType in _dicTypes)
                {
                    _builder.RegisterType(dicType.Value).As(dicType.Key);
                }
            }
 
            _builder.Populate(services);
            _container = _builder.Build();
            return new AutofacServiceProvider(_container);
        }
 
        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T Resolve<T>()
        {
            return _container.Resolve<T>();
        }
 
        public static T Resolve<T>(params Parameter[] parameters)
        {
            return _container.Resolve<T>(parameters);
        }
 
        public static object Resolve(Type targetType)
        {
            return _container.Resolve(targetType);
        }
 
        public static object Resolve(Type targetType, params Parameter[] parameters)
        {
            return _container.Resolve(targetType, parameters);
        }
    }
}

  2、用nuget安装

using Microsoft.Extensions.Configuration;
       using Microsoft.Extensions.DependencyInjection;

3、Program类如下

 1 using BackToCOS.IoC;
 2 using log4net;
 3 using Microsoft.Extensions.Configuration;
 4 using Microsoft.Extensions.DependencyInjection;
 5 using Microsoft.Extensions.Logging;
 6 using Myvas.AspNetCore.TencentCos;
 7 using System;
 8 using System.IO;
 9 using Topshelf;
10
11 namespace BackToCOS
12 {
13     class Program
14     {
15         static void Main(string[] args)
16         {
17             var configuration = new ConfigurationBuilder()
18               .SetBasePath(Directory.GetCurrentDirectory())
19               .AddJsonFile("appsettings.json", true, true)
20               .AddJsonFile("appsettings.Development.json", true, true)
21               .Build();
22             IServiceCollection services = new ServiceCollection();
23
24             services.AddTencentCos(options =>
25             {
26                 options.SecretId = configuration["TencentCos:SecretId"];
27                 options.SecretKey = configuration["TencentCos:SecretKey"];
28             });
29             services.AddLogging(builder => builder
30                .AddConfiguration(configuration.GetSection("Logging"))
31                .AddConsole());
32             //注入
33             services.AddSingleton<ITencentCosHandler, TencentCosHandler>();
34             //用Autofac接管
35             AutofacContainer.Build(services);
36             log4net.Config.XmlConfigurator.ConfigureAndWatch(LogManager.CreateRepository("NETCoreRepository"), new FileInfo(AppDomain.CurrentDomain.BaseDirectory + "log4net.config"));
37             HostFactory.Run(x =>
38             {
39                 x.UseLog4Net();
40                 x.Service<BackupServiceRunner>();
41                 x.RunAsLocalSystem();
42                 x.SetDescription("备份到cos的服务");
43                 x.SetDisplayName("备份到cos的服务");
44                 x.SetServiceName("BackToCOS");
45                 x.EnablePauseAndContinue();
46             });
47         }
48     }
49
50 }

4、用容器获取事例(非构造函数)

 1 using log4net;
 2 using Microsoft.Extensions.Options;
 3 using Myvas.AspNetCore.TencentCos;
 4 using Quartz;
 5 using System;
 6 using System.Collections.Generic;
 7 using System.Text;
 8 using System.Threading.Tasks;
 9
10 namespace BackToCOS.Jobs
11 {
12     //DisallowConcurrentExecution属性标记任务不可并行
13     [DisallowConcurrentExecution]
14     public class BackupJob : IJob
15     {
16         private readonly ILog _log = LogManager.GetLogger("NETCoreRepository", typeof(BackupJob));
17         public Task Execute(IJobExecutionContext context)
18         {
19             try
20             {
21                 _log.Info("测试任务,当前系统时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
22                 ITencentCosHandler tencentCosHandler = IoC.AutofacContainer.Resolve<ITencentCosHandler>();
23                 var ss = tencentCosHandler.AllBucketsAsync();
24                 return Task.CompletedTask;
25             }
26             catch (Exception ex)
27             {
28                 JobExecutionException e2 = new JobExecutionException(ex);
29                 _log.Error("测试任务异常", ex);
30             }
31             return Task.CompletedTask;
32         }
33     }
34 }

大比速:remoting、WCF(http)、WCF(tcp)、WCF(RESTful)、asp.net core(RESTful) .net core 控制台程序使用依赖注入(Autofac)的更多相关文章

  1. 大比速:remoting、WCF(http)、WCF(tcp)、WCF(RESTful)、asp.net core(RESTful)

    近来在考虑一个服务选型,dotnet提供了众多的远程服务形式.在只考虑dotnet到dotnet的情形下,我们可以选择remoting.WCF(http).WCF(tcp).WCF(RESTful). ...

  2. WCF 采用net.tcp协议

    WCF 采用net.tcp协议实践   概述 与Socket相比,WCF真是爽得不得了,其基本指导思想为SOA——面向服务. 其基本配置在于ABC(Address,Binding,Contract), ...

  3. 如何在wcf中用net tcp协议进行通讯

    快速阅读 如何在wcf中用net tcp协议进行通讯,一个打开Wcf的公共类.比较好好,可以记下来. 配置文件中注意配置 Service,binding,behaviors. Service中配置en ...

  4. WCF入门教程:WCF基础知识问与答(转)

    学习WCF已有近两年的时间,其间又翻译了Juval的大作<Programming WCF Services>,我仍然觉得WCF还有更多的内容值得探索与挖掘.学得越多,反而越发觉得自己所知太 ...

  5. Webservice WCF WebApi 前端数据可视化 前端数据可视化 C# asp.net PhoneGap html5 C# Where 网站分布式开发简介 EntityFramework Core依赖注入上下文方式不同造成内存泄漏了解一下? SQL Server之深入理解STUFF 你必须知道的EntityFramework 6.x和EntityFramework Cor

    Webservice WCF WebApi   注明:改编加组合 在.net平台下,有大量的技术让你创建一个HTTP服务,像Web Service,WCF,现在又出了Web API.在.net平台下, ...

  6. WCF服务端的.NET Core支持项目Core WCF 正式启动

    长期以来在wcf客户端库 https://github.com/dotnet/wcf 里反应最强烈的就是.NET Core的服务端支持 https://github.com/dotnet/wcf/is ...

  7. WCF学习之旅—WCF服务的批量寄宿(十三)

    上接    WCF学习之旅—WCF服务部署到IIS7.5(九) WCF学习之旅—WCF服务部署到应用程序(十) WCF学习之旅—WCF服务的Windows 服务程序寄宿(十一) WCF学习之旅—WCF ...

  8. WCF入门教程1——WCF简要介绍

    什么是WCF Windows Communication Foundation(WCF)是由微软开发的一系列支持数据通信的应用程序框架,可以翻译为Windows 通讯开发平台. 整合了原有的windo ...

  9. WCF入门教程三[WCF的宿主]

    一.WCF服务应用程序与WCF服务库 我们在平时开发的过程中常用的项目类型有“WCF 服务应用程序”和“WCF服务库”. WCF服务应用程序,是一个可以执行的程序,它有独立的进程,WCF服务类契约的定 ...

随机推荐

  1. mysql中日期比较大小的方法

    假如有个表product有个字段add_time,它的数据类型为datetime,有人可能会这样写sql: select * from product where add_time = '2013-0 ...

  2. MYSQL Out of resources when opening file './xxx.MYD' (Errcode: 24)

    出现Out of resources when opening file './xxx.MYD' (Errcode: 24)错误是因为打开的文件数超过了my.cnf的--open-files-limi ...

  3. iOS8 NotificationCenter Extension 简介

    在最新的WWDC14上面,苹果发布了iOS8的一些新特性,而其中最让程序员兴奋的特性莫过于Extension,或者称之为Widget. 下面就来尝鲜试验一把. 一.Extension简介 首先,苹果只 ...

  4. hibernate将connection放进threadlocal里实现数据库连接池

    Why ThreadLocal? 无论如何,要编写一个多线程安全(Thread-safe)的程序是困难的,为了让线程共享资源,必须小心地对共享资源进行同步,同步带来一定的效能延迟,而另一方面,在处理同 ...

  5. Jolokia

    Jolokia 是一个用来访问远程 JMX MBeans 的崭新方法,与 JSR-160 连接器不同的是,它使用基于 HTTP 的 JSON 格式作为通讯协议,提供 JMX 批量操作等.需要第三方ja ...

  6. flume和kafka整合(转)

    原文链接:Kafka flume 整合 前提 前提是要先把flume和kafka独立的部分先搭建好. 下载插件包 下载flume-kafka-plus:https://github.com/beyon ...

  7. django from组件 实现增加 删除 编辑(推荐用法)

    实现效果: 代码示例: 代码: models.py from django.db import models class UserInfo(models.Model): username = mode ...

  8. environmentmap in unity

    真崩溃之前明明找到这个api了 然后没存 然后我就找不到了... 刚刚遇到个特别邪门的问题 调着调着 vs的断点都显示无效 重启unity vs 电脑都不好使 之后我双击了breakpoint窗口.. ...

  9. 正向代理/反向代理理解、Nginx概述、安装及配置详解

    一.Nginx概述 nginx是一款自由的.开源的.高性能的HTTP服务器和反向代理服务器:同时也是一个IMAP.POP3.SMTP代理服务器:nginx可以作为一个HTTP服务器进行网站的发布处理, ...

  10. C++primer习题--第1章

    本文地址:http://www.cnblogs.com/archimedes/p/cpp-primer-chapter1-ans.html,转载请注明源地址. [习题 1.3] 编一个程序,在标准输出 ...