Reactor Pattern (一)
Reactor Pattern是一种为处理服务请求并发提交到一个或者多个服务处理程序的事件设计模式,当请求抵达后,服务处理程序使用多路分配策略,然后同步地派发这些请求至相关的请求处理程序。
?
Requester类是请求程序,该类的run方法在连上socket后发生一个自身的标识符requestid, 在main函数中启动10个requester线程,来模拟多用户并发访问的情形。
?
?
?有了这几个类后,再启动server端来处理这些请求就可以构成一个完整的reactor模式的代码。这个类启动serversocket读取requester发送过来的requestid,交给分发器去处理,serversocket闲置30s后自动关闭,另外这个类还注册了一个shutdownhook,在程序异常终止时,确保serversocket被关闭。
?
the request No.[7] is handling the requesting with resource [1]the request No.[8] is handling the requesting with resource [2]the request No.[7] processed the requesting with resource [1]return resource: 1the request No.[8] processed the requesting with resource [2]return resource: 2the request No.[5] is handling the requesting with resource [1]the request No.[1] is handling the requesting with resource [2]the request No.[5] processed the requesting with resource [1]the request No.[1] processed the requesting with resource [2]return resource: 1return resource: 2the request No.[9] is handling the requesting with resource [1]the request No.[4] is handling the requesting with resource [2]the request No.[4] processed the requesting with resource [2]the request No.[9] processed the requesting with resource [1]return resource: 1return resource: 2the request No.[0] is handling the requesting with resource [1]the request No.[3] is handling the requesting with resource [2]the request No.[0] processed the requesting with resource [1]the request No.[3] processed the requesting with resource [2]return resource: 1return resource: 2the request No.[2] is handling the requesting with resource [1]the request No.[6] is handling the requesting with resource [2]the request No.[2] processed the requesting with resource [1]return resource: 1the request No.[6] processed the requesting with resource [2]return resource: 2??
小结
?
Reactor模式在分发资源和归还资源的时候是同步的,在处理请求的时候,是异步的,实际使用中,真正的业务代码会被放到请求处理程序之中。
?
附件中有完整的代码共大家学习研究。
?
[原创内容,版权所有,如果转载,请注明出处]