动态代理配合rpc技术调用远程服务,不用关注细节的实现,让程序就像在本地调用以用。

因此动态代理在微服务系统中是不可或缺的一个技术。网上看到大部分案例都是通过反射自己实现,且相当复杂。编写和调试相当不易,我这里提供里一种简便的方式来实现动态代理。

1、创建我们的空白.netcore项目 

通过vs2017轻易的创建出一个.netcore项目

2、编写startup.cs文件

默认startup 没有构造函数,自行添加构造函数,带有  iconfiguration 参数的,用于获取项目配置,但我们的示例中未使用配置

  public startup(iconfiguration configuration)
        {
            configuration = configuration;
            //注册编码提供程序
            encoding.registerprovider(codepagesencodingprovider.instance);
        }

在configureservices 配置日志模块,目前core更新的很快,日志的配置方式和原来又很大出入,最新的配置方式如下

  // for more information on how to configure your application, visit https://go.microsoft.com/fwlink/?linkid=398940
        public void configureservices(iservicecollection services  )
        {
            services.addlogging(loggingbuilder=> {
                loggingbuilder.addconfiguration(configuration.getsection("logging"));
                loggingbuilder.addconsole();
                loggingbuilder.adddebug();
            });

        }

添加路由过滤器,监控一个地址,用于调用我们的测试代码。netcore默认没有utf8的编码方式,所以要先解决utf8编码问题,否则将在输出中文时候乱码。

这里注意 map  内部传递了参数 applicationbuilder ,千万不要 使用configure(iapplicationbuilder app, ihostingenvironment env ) 中的app参数,否则每次请求api/health时候都将调用这个中间件(app.run会短路期后边所有的中间件),

 app.map("/api/health", (applicationbuilder) =>
            {

                applicationbuilder.run(context =>
               {
                   return context.response.writeasync(uname.result, encoding.utf8);
               });
            });

 

3、代理

netcore 已经为我们完成了一些工作,提供了dispatchproxy 这个类

#region 程序集 system.reflection.dispatchproxy, version=4.0.4.0, culture=neutral, publickeytoken=b03f5f7f11d50a3a
// c:\program files\dotnet\sdk\nugetfallbackfolder\microsoft.netcore.app.2.0\ref\netcoreapp2.2\system.reflection.dispatchproxy.dll
#endregion

namespace system.reflection
{
    //
    public abstract class dispatchproxy
    {
        //
        protected dispatchproxy();

        //
        // 类型参数:
        //   t:
        //
        //   tproxy:
        public static t create<t, tproxy>() where tproxy : dispatchproxy;
        //
        // 参数:
        //   targetmethod:
        //
        //   args:
        protected abstract object invoke(methodinfo targetmethod, object[] args);
    }
}

这个类提供了一个实例方法,一个静态方法:

invoke(methodinfo targetmethod, object[] args) 注解1

create<t, tproxy>()注解2

create 创建代理的实例对象,实例对象在调用方法时候会自动执行invoke

 

 

首先我们创建一个动态代理类  proxydecorator<t>:dispatchproxy  需要继承dispatchproxy 

在dispatchproxy 的静态方法  create<t, tproxy>()中要求 tproxy : dispatchproxy

proxydecorator 重写  dispatchproxy的虚方法invoke 

我们可以在proxydecorator 类中添加一些其他方法,比如:异常处理,methodinfo执行前后的处理。

重点要讲一下 

proxydecorator 中需要传递一个 t类型的变量 decorated 。

因为  dispatchproxy.create<t, proxydecorator<t>>(); 会创建一个新的t的实例对象 ,这个对象是代理对象实例,我们将 decorated 绑定到这个代理实例上

接下来这个代理实例在执行t类型的任何方法时候都会用到 decorated,因为 [decorated] 会被传给  targetmethod.invoke(decorated, args)   (targetmethod 来自注解1) ,invoke相当于执行

这样说的不是很明白,我们直接看代码

  1 using system;
  2 using system.collections.generic;
  3 using system.linq;
  4 using system.linq.expressions;
  5 using system.reflection;
  6 using system.text;
  7 using system.threading.tasks;
  8 
  9 namespace testwfw
 10 {
 11     public class proxydecorator<t> : dispatchproxy
 12     {
 13         //关键词 realproxy
 14         private t decorated;
 15         private event action<methodinfo, object[]> _afteraction;   //动作之后执行
 16         private event action<methodinfo, object[]> _beforeaction;   //动作之前执行
 17 
 18         //其他自定义属性,事件和方法
 19         public proxydecorator()
 20         {
 21 
 22         }
 23 
 24 
 25         /// <summary>
 26         /// 创建代理实例
 27         /// </summary>
 28         /// <param name="decorated">代理的接口类型</param>
 29         /// <returns></returns>
 30         public t create(t decorated)
 31         {
 32 
 33             object proxy = create<t, proxydecorator<t>>();   //调用dispatchproxy 的create  创建一个新的t
 34             ((proxydecorator<t>)proxy).decorated = decorated;       //这里必须这样赋值,会自动未proxy 添加一个新的属性
                                            //其他的请如法炮制
 35 

          return (t)proxy; 36 } 37 38 /// <summary> 39 /// 创建代理实例 40 /// </summary> 41 /// <param name="decorated">代理的接口类型</param> 42 /// <param name="beforeaction">方法执行前执行的事件</param> 43 /// <param name="afteraction">方法执行后执行的事件</param> 44 /// <returns></returns> 45 public t create(t decorated, action<methodinfo, object[]> beforeaction, action<methodinfo, object[]> afteraction) 46 { 47 48 object proxy = create<t, proxydecorator<t>>(); //调用dispatchproxy 的create 创建一个新的t 49 ((proxydecorator<t>)proxy).decorated = decorated; 50 ((proxydecorator<t>)proxy)._afteraction = afteraction; 51 ((proxydecorator<t>)proxy)._beforeaction = beforeaction; 52 //((genericdecorator<t>)proxy)._loggingscheduler = taskscheduler.fromcurrentsynchronizationcontext(); 53 return (t)proxy; 54 } 55 56 57 58 protected override object invoke(methodinfo targetmethod, object[] args) 59 { 60 if (targetmethod == null) throw new exception("无效的方法"); 61 62 try 63 { 64 //_beforeaction 事件 65 if (_beforeaction != null) 66 { 67 this._beforeaction(targetmethod, args); 68 } 69 70 71 object result = targetmethod.invoke(decorated, args); 72              system.diagnostics.debug.writeline(result);      //打印输出面板 73 var resulttask = result as task; 74 if (resulttask != null) 75 { 76 resulttask.continuewith(task => //continuewith 创建一个延续,该延续接收调用方提供的状态信息并执行 当目标系统 tasks。 77 { 78 if (task.exception != null) 79 { 80 logexception(task.exception.innerexception ?? task.exception, targetmethod); 81 } 82 else 83 { 84 object taskresult = null; 85 if (task.gettype().gettypeinfo().isgenerictype && 86 task.gettype().getgenerictypedefinition() == typeof(task<>)) 87 { 88 var property = task.gettype().gettypeinfo().getproperties().firstordefault(p => p.name == "result"); 89 if (property != null) 90 { 91 taskresult = property.getvalue(task); 92 } 93 } 94 if (_afteraction != null) 95 { 96 this._afteraction(targetmethod, args); 97 } 98 } 99 }); 100 } 101 else 102 { 103 try 104 { 105 // _afteraction 事件 106 if (_afteraction != null) 107 { 108 this._afteraction(targetmethod, args); 109 } 110 } 111 catch (exception ex) 112 { 113 //do not stop method execution if exception 114 logexception(ex); 115 } 116 } 117 118 return result; 119 } 120 catch (exception ex) 121 { 122 if (ex is targetinvocationexception) 123 { 124 logexception(ex.innerexception ?? ex, targetmethod); 125 throw ex.innerexception ?? ex; 126 } 127 else 128 { 129 throw ex; 130 } 131 } 132 133 } 134 135 136 /// <summary> 137 /// aop异常的处理 138 /// </summary> 139 /// <param name="exception"></param> 140 /// <param name="methodinfo"></param> 141 private void logexception(exception exception, methodinfo methodinfo = null) 142 { 143 try 144 { 145 var errormessage = new stringbuilder(); 146 errormessage.appendline($"class {decorated.gettype().fullname}"); 147 errormessage.appendline($"method {methodinfo?.name} threw exception"); 148 errormessage.appendline(exception.message); 149 150 //_logerror?.invoke(errormessage.tostring()); 记录到文件系统 151 } 152 catch (exception) 153 { 154 // ignored 155 //method should return original exception 156 } 157 } 158 } 159 }

 

代码比较简单,相信大家都看的懂,关键的代码和核心的系统代码已经加粗和加加粗+红 标注出来了

dispatchproxy<t> 类中有两种创建代理实例的方法

我们看一下第一种比较简单的创建方法

        // this method gets called by the runtime. use this method to configure the http request pipeline.
        public void configure(iapplicationbuilder app, ihostingenvironment env )
        {
            if (env.isdevelopment())
            {
                app.usedeveloperexceptionpage();
            }



            // 添加健康检查路由地址
            app.map("/api/health", (applicationbuilder) =>
            {

                applicationbuilder.run(context =>
               {
                   iuserservice userservice = new userservice();
                   //执行代理
                   var serviceproxy = new proxydecorator<iuserservice>();
                   iuserservice user = serviceproxy.create(userservice);  //
                   task<string> uname = user.getusername(222);
                   context.response.contenttype = "text/plain;charset=utf-8";

                   return context.response.writeasync(uname.result, encoding.utf8);
               });
            });
}

代码中 userservice 和 iuserservice 是一个class和interface  自己实现即可 ,随便写一个接口,并用类实现,任何一个方法就行,下面只是演示调用方法时候会执行什么,这个方法本身在岩石中并不重要。

 由于proxydecorator 中并未注入相关事件,所以我们在调用 user.getusername(222) 时候看不到任何特别的输出。下面我们演示一个相对复杂的调用方式。

    // 添加健康检查路由地址
            app.map("/api/health2", (applicationbuilder) =>
            {
                applicationbuilder.run(context =>
                {
                    iuserservice userservice = new userservice();
                    //执行代理
                    var serviceproxy = new proxydecorator<iuserservice>();
                    iuserservice user = serviceproxy.create(userservice, beforeevent, afterevent);  //
                    task<string> uname = user.getusername(222);
                    context.response.contenttype = "text/plain;charset=utf-8";

                    return context.response.writeasync(uname.result, encoding.utf8);

                });
            });

 iuserservice user = serviceproxy.create(userservice, beforeevent, afterevent); 在创建代理实例时候传递了beforevent 和 afterevent,这两个事件处理
函数是我们在业务中定义的

void beforeevent(methodinfo methodinfo, object[] arges)
{
system.diagnostics.debug.writeline(“方法执行前”);
}

void afterevent(methodinfo methodinfo, object[] arges)
{
system.diagnostics.debug.writeline(“执行后的事件”);
}

在代理实例执行接口的任何方法的时候都会执行  beforeevent,和 afterevent 这两个事件(请参考invoke(methodinfo targetmethod, object[] args) 方法的实现)

在我们的示例中将会在vs的 输出 面板中看到 

 

 

方法执行前

“方法输出的值”

执行后事件

我们看下运行效果图:

 

 

 

 这是 user.getusername(222) 的运行结果

 

 控制台输出结果