SlideShare a Scribd company logo
1 of 17
Глава 5. Первая реализация 118
Концепция 119
IMessage 120 
public interface IMessage 
{ 
string Target 
{ 
get; 
} 
}
MessageBus 121 
public class MessageBus 
{ 
public static void Send(IMessage message) 
{…} 
public static void Join( 
string address, 
Actor actor 
) 
{ … } 
}
Actor 122 
public abstract class Actor 
{ 
public Actor(string address) { … } 
public Actor() { … } 
public void Become(Action<IMessage> handler) 
{ … } 
public void Receive(IMessage message) { … } 
public abstract void Handle(IMessage message); 
}
Фасад для IoC 123 
public class DIContainer 
{ 
IContainer container; 
public T Resolve<T>() 
{ 
return container.Resolve<T>(); 
} 
}
Фасад для IoC 124 
Файл: RouterImpl/IoCRegistration.cs 
using Autofac; 
namespace HWdTech.DS.Internals.Implementation 
{ 
class RouterRegistrationModule : Module 
{ 
protected override void Load(ContainerBuilder builder) 
{ 
IRouter router = new RouterImpl(); 
builder.RegisterInstance(router).As<IRouter>(); 
} 
} 
}
Фасад для IoC 125 
public class DIContainer 
{ 
public DIContainer() 
{ 
ContainerBuilder builder = new ContainerBuilder(); 
Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); 
builder.RegisterAssemblyModules(assemblies); 
this.container = builder.Build(); 
AppDomain.CurrentDomain.AssemblyLoad += AssemblyLoadEventHandler; 
} 
void AssemblyLoadEventHandler(object sender, AssemblyLoadEventArgs args) 
{ 
LoadAssembly(args.LoadedAssembly); 
} 
LoadAssembly(Assembly assembly) 
{ 
ContainerBuilder builder = new ContainerBuilder(); 
builder.RegisterAssemblyModules(assembly); 
builder.Update(container); 
} 
}
Реализация MessageBus.Join 126 
static IRouter router; 
public static void Join(string address, Actor actor) 
{ 
if (null == router) 
{ 
router = Singleton<DIContainer>.Instance.Resolve<IRouter>(); 
} 
router.RegisterOrReplace(address, actor.Receive); 
}
Реализация MessageBus.Send 127 
static IThreadPool threadPool; 
public static void Send(IMessage message) 
{ 
if (null == threadPool) { 
threadPool = Singleton<DIContainer>.Instance.Resolve<IThreadPool>(); 
} 
threadPool.StartTask(HandleMessage, message); 
} 
static void HandleMessage(object o) 
{ 
IMessage message = (IMessage) o; 
if (null == router) { 
router = Singleton<DIContainer>.Instance.Resolve<IRouter>(); 
} 
router.Send(message); 
}
Ping-Pong Test 128 
[Test] 
public void PingPongTest() 
{ 
ThreadPoolImpl threadPool = new ThreadPoolImpl(); 
RouterImpl router = new RouterImpl(); 
Mock<IMessage> pingMessage = repository.Create<IMessage>(); 
pingMessage.SetupGet(m => m.Target).Returns("ping"); 
Actor pongActor = new PongActor(pingMessage.Object); 
Mock<IMessage> pongMessage = repository.Create<IMessage>(); 
pongMessage.SetupGet(m => m.Target).Returns("pong"); 
ManualResetEvent waitSignal = new ManualResetEvent(false); 
PingActor pingActor = new PingActor(pongMessage.Object, waitSignal); 
Assert.True(waitSignal.WaitOne(1000)); 
pingActor.Verify(); 
}
Ping-Pong Test: Ping Actor 129 
class PingActor : Actor{ 
int gotMessages; 
IMessage pongMessage; 
ManualResetEvent signal; 
const int numberOfResponsesShoulgGet = 5; 
public PingActor(IMessage pongMessage, ManualResetEvent signal) : base("ping") { 
this.signal = signal; 
this.pongMessage = pongMessage; 
MessageBus.Send(pongMessage); 
} 
public override void Handle(IMessage message) { 
++gotMessages; 
if (numberOfResponsesShoulgGet > gotMessages) { 
MessageBus.Send(pongMessage); 
} 
else { signal.Set(); } 
} 
public void Verify() { 
Assert.AreEqual(numberOfResponsesShoulgGet, gotMessages); 
} 
}
Ping-Pong Test: Pong Actor 130 
class PongActor : Actor 
{ 
IMessage pingMessage; 
public PongActor(IMessage pingMessage) 
: base("pong") 
{ 
this.pingMessage = pingMessage; 
} 
public override void Handle(IMessage message) 
{ 
MessageBus.Send(pingMessage); 
} 
}
Фасад для ThreadPool 131 
public interface IThreadPool 
{ 
void StartTask(Action<object> task, object arg); 
} 
public class ThreadPoolImpl : IThreadPool 
{ 
public void StartTask(Action<object> action, object args = null) 
{ 
System.Threading.ThreadPool.QueueUserWorkItem(new 
System.Threading.WaitCallback(action), args); 
} 
}
Пример теста для ThreadPool 132 
[Test] 
public void ThreadPoolShouldRunTasksWithArgument() 
{ 
System.Threading.ManualResetEvent canContinue = new 
System.Threading.ManualResetEvent(false); 
ThreadPoolImpl pool = new ThreadPoolImpl(); 
object o = new object(); 
bool gotArgument = false; 
pool.StartTask((obj) => { 
gotArgument = object.ReferenceEquals(obj, o); 
canContinue.Set(); 
}, o); 
Assert.True(canContinue.WaitOne(1000)); 
Assert.True(gotArgument); 
}
Фасад для роутера 133 
public interface IRouter 
{ 
void Send(IMessage message); 
IRouter RegisterOrReplace(string channel, Action<IMessage> handler); 
}
Фасад для роутера 134 
public class RouterImpl: IRouter { 
public RouterImpl() { 
routerImpl = new ConcurrentDictionary<string, Action<IMessage>>(); 
} 
public void Send(IMessage message) 
{ 
Action<IMessage> handler; 
if (routerImpl.TryGetValue(message.Target, out handler)) { 
handler(message); 
} 
else { //ToDo: адресат неизвестен - надо разрешить с помощью внешнего сервиса. 
} 
} 
public IRouter RegisterOrReplace(string channel, Action<IMessage> handler) 
{ 
routerImpl.AddOrUpdate(channel, handler, (key, oldValue) => { return handler; }); 
return this; 
} 
ConcurrentDictionary<string, Action<IMessage>> routerImpl; 
}

More Related Content

What's hot

Dagger & rxjava & retrofit
Dagger & rxjava & retrofitDagger & rxjava & retrofit
Dagger & rxjava & retrofitTed Liang
 
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coinsoft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coinsoft-shake.ch
 
Software Testing - Invited Lecture at UNSW Sydney
Software Testing - Invited Lecture at UNSW SydneySoftware Testing - Invited Lecture at UNSW Sydney
Software Testing - Invited Lecture at UNSW Sydneyjulien.ponge
 
Reactive programming with RxAndroid
Reactive programming with RxAndroidReactive programming with RxAndroid
Reactive programming with RxAndroidSavvycom Savvycom
 
Testing in android
Testing in androidTesting in android
Testing in androidjtrindade
 
Java Concurrency Idioms
Java Concurrency IdiomsJava Concurrency Idioms
Java Concurrency IdiomsAlex Miller
 
The Future of Futures - A Talk About Java 8 CompletableFutures
The Future of Futures - A Talk About Java 8 CompletableFuturesThe Future of Futures - A Talk About Java 8 CompletableFutures
The Future of Futures - A Talk About Java 8 CompletableFuturesHaim Yadid
 
Behind modern concurrency primitives
Behind modern concurrency primitivesBehind modern concurrency primitives
Behind modern concurrency primitivesBartosz Sypytkowski
 
Concurrent Programming in Java
Concurrent Programming in JavaConcurrent Programming in Java
Concurrent Programming in JavaRuben Inoto Soto
 
Akka.NET streams and reactive streams
Akka.NET streams and reactive streamsAkka.NET streams and reactive streams
Akka.NET streams and reactive streamsBartosz Sypytkowski
 
Java nio ( new io )
Java nio ( new io )Java nio ( new io )
Java nio ( new io )Jemin Patel
 
The Ring programming language version 1.7 book - Part 52 of 196
The Ring programming language version 1.7 book - Part 52 of 196The Ring programming language version 1.7 book - Part 52 of 196
The Ring programming language version 1.7 book - Part 52 of 196Mahmoud Samir Fayed
 
The Ring programming language version 1.5.2 book - Part 13 of 181
The Ring programming language version 1.5.2 book - Part 13 of 181The Ring programming language version 1.5.2 book - Part 13 of 181
The Ring programming language version 1.5.2 book - Part 13 of 181Mahmoud Samir Fayed
 
망고100 보드로 놀아보자 19
망고100 보드로 놀아보자 19망고100 보드로 놀아보자 19
망고100 보드로 놀아보자 19종인 전
 

What's hot (19)

Dagger & rxjava & retrofit
Dagger & rxjava & retrofitDagger & rxjava & retrofit
Dagger & rxjava & retrofit
 
Current State of Coroutines
Current State of CoroutinesCurrent State of Coroutines
Current State of Coroutines
 
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coinsoft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
 
Software Testing - Invited Lecture at UNSW Sydney
Software Testing - Invited Lecture at UNSW SydneySoftware Testing - Invited Lecture at UNSW Sydney
Software Testing - Invited Lecture at UNSW Sydney
 
Reactive programming with RxAndroid
Reactive programming with RxAndroidReactive programming with RxAndroid
Reactive programming with RxAndroid
 
Thread
ThreadThread
Thread
 
JAVA NIO
JAVA NIOJAVA NIO
JAVA NIO
 
devday2012
devday2012devday2012
devday2012
 
Testing in android
Testing in androidTesting in android
Testing in android
 
Java Concurrency Idioms
Java Concurrency IdiomsJava Concurrency Idioms
Java Concurrency Idioms
 
The Future of Futures - A Talk About Java 8 CompletableFutures
The Future of Futures - A Talk About Java 8 CompletableFuturesThe Future of Futures - A Talk About Java 8 CompletableFutures
The Future of Futures - A Talk About Java 8 CompletableFutures
 
Behind modern concurrency primitives
Behind modern concurrency primitivesBehind modern concurrency primitives
Behind modern concurrency primitives
 
Concurrent Programming in Java
Concurrent Programming in JavaConcurrent Programming in Java
Concurrent Programming in Java
 
Akka.NET streams and reactive streams
Akka.NET streams and reactive streamsAkka.NET streams and reactive streams
Akka.NET streams and reactive streams
 
NIO and NIO2
NIO and NIO2NIO and NIO2
NIO and NIO2
 
Java nio ( new io )
Java nio ( new io )Java nio ( new io )
Java nio ( new io )
 
The Ring programming language version 1.7 book - Part 52 of 196
The Ring programming language version 1.7 book - Part 52 of 196The Ring programming language version 1.7 book - Part 52 of 196
The Ring programming language version 1.7 book - Part 52 of 196
 
The Ring programming language version 1.5.2 book - Part 13 of 181
The Ring programming language version 1.5.2 book - Part 13 of 181The Ring programming language version 1.5.2 book - Part 13 of 181
The Ring programming language version 1.5.2 book - Part 13 of 181
 
망고100 보드로 놀아보자 19
망고100 보드로 놀아보자 19망고100 보드로 놀아보자 19
망고100 보드로 놀아보자 19
 

Viewers also liked

Большие данные: как могут навредить и ка могут помочь?
Большие данные: как могут навредить и ка могут помочь?Большие данные: как могут навредить и ка могут помочь?
Большие данные: как могут навредить и ка могут помочь?etyumentcev
 
Математическое обоснование S.O.L.I.D принципов
Математическое обоснование S.O.L.I.D принциповМатематическое обоснование S.O.L.I.D принципов
Математическое обоснование S.O.L.I.D принциповetyumentcev
 
Как 7 студентов и филолог делали сложный проект
Как 7 студентов и филолог делали сложный проектКак 7 студентов и филолог делали сложный проект
Как 7 студентов и филолог делали сложный проектetyumentcev
 
Как жить в согласии с SOLID?
Как жить в согласии с SOLID?Как жить в согласии с SOLID?
Как жить в согласии с SOLID?etyumentcev
 
Программирование глазами математика
Программирование глазами математикаПрограммирование глазами математика
Программирование глазами математикаetyumentcev
 
Платформа SmartActors
Платформа SmartActorsПлатформа SmartActors
Платформа SmartActorsetyumentcev
 
матлогика для программистов
матлогика для программистовматлогика для программистов
матлогика для программистовetyumentcev
 
математическое обоснование Solid принципов. Конференция dotnetconf (Челябинск...
математическое обоснование Solid принципов. Конференция dotnetconf (Челябинск...математическое обоснование Solid принципов. Конференция dotnetconf (Челябинск...
математическое обоснование Solid принципов. Конференция dotnetconf (Челябинск...etyumentcev
 
Об опыте применения jsonb в реальных проектах. Выступление на PgConf.Russia 2016
Об опыте применения jsonb в реальных проектах. Выступление на PgConf.Russia 2016Об опыте применения jsonb в реальных проектах. Выступление на PgConf.Russia 2016
Об опыте применения jsonb в реальных проектах. Выступление на PgConf.Russia 2016etyumentcev
 

Viewers also liked (9)

Большие данные: как могут навредить и ка могут помочь?
Большие данные: как могут навредить и ка могут помочь?Большие данные: как могут навредить и ка могут помочь?
Большие данные: как могут навредить и ка могут помочь?
 
Математическое обоснование S.O.L.I.D принципов
Математическое обоснование S.O.L.I.D принциповМатематическое обоснование S.O.L.I.D принципов
Математическое обоснование S.O.L.I.D принципов
 
Как 7 студентов и филолог делали сложный проект
Как 7 студентов и филолог делали сложный проектКак 7 студентов и филолог делали сложный проект
Как 7 студентов и филолог делали сложный проект
 
Как жить в согласии с SOLID?
Как жить в согласии с SOLID?Как жить в согласии с SOLID?
Как жить в согласии с SOLID?
 
Программирование глазами математика
Программирование глазами математикаПрограммирование глазами математика
Программирование глазами математика
 
Платформа SmartActors
Платформа SmartActorsПлатформа SmartActors
Платформа SmartActors
 
матлогика для программистов
матлогика для программистовматлогика для программистов
матлогика для программистов
 
математическое обоснование Solid принципов. Конференция dotnetconf (Челябинск...
математическое обоснование Solid принципов. Конференция dotnetconf (Челябинск...математическое обоснование Solid принципов. Конференция dotnetconf (Челябинск...
математическое обоснование Solid принципов. Конференция dotnetconf (Челябинск...
 
Об опыте применения jsonb в реальных проектах. Выступление на PgConf.Russia 2016
Об опыте применения jsonb в реальных проектах. Выступление на PgConf.Russia 2016Об опыте применения jsonb в реальных проектах. Выступление на PgConf.Russia 2016
Об опыте применения jsonb в реальных проектах. Выступление на PgConf.Russia 2016
 

Similar to разработка серверов и серверных приложений лекция №4

.NET Multithreading and File I/O
.NET Multithreading and File I/O.NET Multithreading and File I/O
.NET Multithreading and File I/OJussi Pohjolainen
 
What’s new in C# 6
What’s new in C# 6What’s new in C# 6
What’s new in C# 6Fiyaz Hasan
 
Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical FileSoumya Behera
 
ikh331-06-distributed-programming
ikh331-06-distributed-programmingikh331-06-distributed-programming
ikh331-06-distributed-programmingAnung Ariwibowo
 
Implementing CQRS and Event Sourcing with RavenDB
Implementing CQRS and Event Sourcing with RavenDBImplementing CQRS and Event Sourcing with RavenDB
Implementing CQRS and Event Sourcing with RavenDBOren Eini
 
Java осень 2012 лекция 2
Java осень 2012 лекция 2Java осень 2012 лекция 2
Java осень 2012 лекция 2Technopark
 
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...tdc-globalcode
 
Durable functions 2.0 (2019-10-10)
Durable functions 2.0 (2019-10-10)Durable functions 2.0 (2019-10-10)
Durable functions 2.0 (2019-10-10)Paco de la Cruz
 
Hi, I need some one to help me with Design a client-server Chat so.pdf
Hi, I need some one to help me with Design a client-server Chat so.pdfHi, I need some one to help me with Design a client-server Chat so.pdf
Hi, I need some one to help me with Design a client-server Chat so.pdffashiongallery1
 
Java весна 2013 лекция 2
Java весна 2013 лекция 2Java весна 2013 лекция 2
Java весна 2013 лекция 2Technopark
 
Laporan multiclient chatting client server
Laporan multiclient chatting client serverLaporan multiclient chatting client server
Laporan multiclient chatting client servertrilestari08
 
The uniform interface is 42
The uniform interface is 42The uniform interface is 42
The uniform interface is 42Yevhen Bobrov
 
Android Loaders : Reloaded
Android Loaders : ReloadedAndroid Loaders : Reloaded
Android Loaders : Reloadedcbeyls
 

Similar to разработка серверов и серверных приложений лекция №4 (20)

.NET Multithreading and File I/O
.NET Multithreading and File I/O.NET Multithreading and File I/O
.NET Multithreading and File I/O
 
What’s new in C# 6
What’s new in C# 6What’s new in C# 6
What’s new in C# 6
 
Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical File
 
ikh331-06-distributed-programming
ikh331-06-distributed-programmingikh331-06-distributed-programming
ikh331-06-distributed-programming
 
Implementing CQRS and Event Sourcing with RavenDB
Implementing CQRS and Event Sourcing with RavenDBImplementing CQRS and Event Sourcing with RavenDB
Implementing CQRS and Event Sourcing with RavenDB
 
Java Concurrency
Java ConcurrencyJava Concurrency
Java Concurrency
 
Java осень 2012 лекция 2
Java осень 2012 лекция 2Java осень 2012 лекция 2
Java осень 2012 лекция 2
 
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...
 
Durable functions 2.0 (2019-10-10)
Durable functions 2.0 (2019-10-10)Durable functions 2.0 (2019-10-10)
Durable functions 2.0 (2019-10-10)
 
Code Samples
Code SamplesCode Samples
Code Samples
 
Akka
AkkaAkka
Akka
 
Hi, I need some one to help me with Design a client-server Chat so.pdf
Hi, I need some one to help me with Design a client-server Chat so.pdfHi, I need some one to help me with Design a client-server Chat so.pdf
Hi, I need some one to help me with Design a client-server Chat so.pdf
 
Java весна 2013 лекция 2
Java весна 2013 лекция 2Java весна 2013 лекция 2
Java весна 2013 лекция 2
 
Laporan multiclient chatting client server
Laporan multiclient chatting client serverLaporan multiclient chatting client server
Laporan multiclient chatting client server
 
The uniform interface is 42
The uniform interface is 42The uniform interface is 42
The uniform interface is 42
 
IoT Best practices
 IoT Best practices IoT Best practices
IoT Best practices
 
Java practical
Java practicalJava practical
Java practical
 
Android Loaders : Reloaded
Android Loaders : ReloadedAndroid Loaders : Reloaded
Android Loaders : Reloaded
 
TDD Hands-on
TDD Hands-onTDD Hands-on
TDD Hands-on
 
Multithreading in Java
Multithreading in JavaMultithreading in Java
Multithreading in Java
 

More from etyumentcev

разработка серверов и серверных приложений лекция №3
разработка серверов и серверных приложений лекция №3разработка серверов и серверных приложений лекция №3
разработка серверов и серверных приложений лекция №3etyumentcev
 
разработка серверов и серверных приложений лекция №2
разработка серверов и серверных приложений лекция №2разработка серверов и серверных приложений лекция №2
разработка серверов и серверных приложений лекция №2etyumentcev
 
разработка серверов и серверных приложений лекция №1
разработка серверов и серверных приложений лекция №1разработка серверов и серверных приложений лекция №1
разработка серверов и серверных приложений лекция №1etyumentcev
 
высокопроизводиетльные системы без доп затрат
высокопроизводиетльные системы без доп затратвысокопроизводиетльные системы без доп затрат
высокопроизводиетльные системы без доп затратetyumentcev
 
зачем нужны системы управления проектами
зачем нужны системы управления проектамизачем нужны системы управления проектами
зачем нужны системы управления проектамиetyumentcev
 
введение в Sql
введение в Sqlвведение в Sql
введение в Sqletyumentcev
 
почему буксует тайм менеджмент
почему буксует тайм менеджментпочему буксует тайм менеджмент
почему буксует тайм менеджментetyumentcev
 
ук 03.011.01 2011
ук 03.011.01 2011ук 03.011.01 2011
ук 03.011.01 2011etyumentcev
 
ук 03.010.01 2011
ук 03.010.01 2011ук 03.010.01 2011
ук 03.010.01 2011etyumentcev
 
ук 03.009.01 2011
ук 03.009.01 2011ук 03.009.01 2011
ук 03.009.01 2011etyumentcev
 
ук 03.007.02 2011
ук 03.007.02 2011ук 03.007.02 2011
ук 03.007.02 2011etyumentcev
 
ук 03.006.02 2011
ук 03.006.02 2011ук 03.006.02 2011
ук 03.006.02 2011etyumentcev
 
ук 03.005.03 2011
ук 03.005.03 2011ук 03.005.03 2011
ук 03.005.03 2011etyumentcev
 
ук 03.003.01 2011
ук 03.003.01 2011ук 03.003.01 2011
ук 03.003.01 2011etyumentcev
 
ук 03.001.02 2011
ук 03.001.02 2011ук 03.001.02 2011
ук 03.001.02 2011etyumentcev
 
ук 03.002.01 2011
ук 03.002.01 2011ук 03.002.01 2011
ук 03.002.01 2011etyumentcev
 
ук 03.005.02 2011
ук 03.005.02 2011ук 03.005.02 2011
ук 03.005.02 2011etyumentcev
 
управление задачами
управление задачамиуправление задачами
управление задачамиetyumentcev
 

More from etyumentcev (20)

разработка серверов и серверных приложений лекция №3
разработка серверов и серверных приложений лекция №3разработка серверов и серверных приложений лекция №3
разработка серверов и серверных приложений лекция №3
 
разработка серверов и серверных приложений лекция №2
разработка серверов и серверных приложений лекция №2разработка серверов и серверных приложений лекция №2
разработка серверов и серверных приложений лекция №2
 
разработка серверов и серверных приложений лекция №1
разработка серверов и серверных приложений лекция №1разработка серверов и серверных приложений лекция №1
разработка серверов и серверных приложений лекция №1
 
высокопроизводиетльные системы без доп затрат
высокопроизводиетльные системы без доп затратвысокопроизводиетльные системы без доп затрат
высокопроизводиетльные системы без доп затрат
 
зачем нужны системы управления проектами
зачем нужны системы управления проектамизачем нужны системы управления проектами
зачем нужны системы управления проектами
 
введение в Sql
введение в Sqlвведение в Sql
введение в Sql
 
почему буксует тайм менеджмент
почему буксует тайм менеджментпочему буксует тайм менеджмент
почему буксует тайм менеджмент
 
ук 03.011.01 2011
ук 03.011.01 2011ук 03.011.01 2011
ук 03.011.01 2011
 
ук 03.010.01 2011
ук 03.010.01 2011ук 03.010.01 2011
ук 03.010.01 2011
 
ук 03.009.01 2011
ук 03.009.01 2011ук 03.009.01 2011
ук 03.009.01 2011
 
ук 03.007.02 2011
ук 03.007.02 2011ук 03.007.02 2011
ук 03.007.02 2011
 
ук 03.006.02 2011
ук 03.006.02 2011ук 03.006.02 2011
ук 03.006.02 2011
 
ук 03.005.03 2011
ук 03.005.03 2011ук 03.005.03 2011
ук 03.005.03 2011
 
ук 03.003.01 2011
ук 03.003.01 2011ук 03.003.01 2011
ук 03.003.01 2011
 
ук 03.001.02 2011
ук 03.001.02 2011ук 03.001.02 2011
ук 03.001.02 2011
 
ук 03.002.01 2011
ук 03.002.01 2011ук 03.002.01 2011
ук 03.002.01 2011
 
ук 03.005.02 2011
ук 03.005.02 2011ук 03.005.02 2011
ук 03.005.02 2011
 
трпо
трпотрпо
трпо
 
ооп
оопооп
ооп
 
управление задачами
управление задачамиуправление задачами
управление задачами
 

Recently uploaded

Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceanilsa9823
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 

Recently uploaded (20)

Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 

разработка серверов и серверных приложений лекция №4

  • 1. Глава 5. Первая реализация 118
  • 3. IMessage 120 public interface IMessage { string Target { get; } }
  • 4. MessageBus 121 public class MessageBus { public static void Send(IMessage message) {…} public static void Join( string address, Actor actor ) { … } }
  • 5. Actor 122 public abstract class Actor { public Actor(string address) { … } public Actor() { … } public void Become(Action<IMessage> handler) { … } public void Receive(IMessage message) { … } public abstract void Handle(IMessage message); }
  • 6. Фасад для IoC 123 public class DIContainer { IContainer container; public T Resolve<T>() { return container.Resolve<T>(); } }
  • 7. Фасад для IoC 124 Файл: RouterImpl/IoCRegistration.cs using Autofac; namespace HWdTech.DS.Internals.Implementation { class RouterRegistrationModule : Module { protected override void Load(ContainerBuilder builder) { IRouter router = new RouterImpl(); builder.RegisterInstance(router).As<IRouter>(); } } }
  • 8. Фасад для IoC 125 public class DIContainer { public DIContainer() { ContainerBuilder builder = new ContainerBuilder(); Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); builder.RegisterAssemblyModules(assemblies); this.container = builder.Build(); AppDomain.CurrentDomain.AssemblyLoad += AssemblyLoadEventHandler; } void AssemblyLoadEventHandler(object sender, AssemblyLoadEventArgs args) { LoadAssembly(args.LoadedAssembly); } LoadAssembly(Assembly assembly) { ContainerBuilder builder = new ContainerBuilder(); builder.RegisterAssemblyModules(assembly); builder.Update(container); } }
  • 9. Реализация MessageBus.Join 126 static IRouter router; public static void Join(string address, Actor actor) { if (null == router) { router = Singleton<DIContainer>.Instance.Resolve<IRouter>(); } router.RegisterOrReplace(address, actor.Receive); }
  • 10. Реализация MessageBus.Send 127 static IThreadPool threadPool; public static void Send(IMessage message) { if (null == threadPool) { threadPool = Singleton<DIContainer>.Instance.Resolve<IThreadPool>(); } threadPool.StartTask(HandleMessage, message); } static void HandleMessage(object o) { IMessage message = (IMessage) o; if (null == router) { router = Singleton<DIContainer>.Instance.Resolve<IRouter>(); } router.Send(message); }
  • 11. Ping-Pong Test 128 [Test] public void PingPongTest() { ThreadPoolImpl threadPool = new ThreadPoolImpl(); RouterImpl router = new RouterImpl(); Mock<IMessage> pingMessage = repository.Create<IMessage>(); pingMessage.SetupGet(m => m.Target).Returns("ping"); Actor pongActor = new PongActor(pingMessage.Object); Mock<IMessage> pongMessage = repository.Create<IMessage>(); pongMessage.SetupGet(m => m.Target).Returns("pong"); ManualResetEvent waitSignal = new ManualResetEvent(false); PingActor pingActor = new PingActor(pongMessage.Object, waitSignal); Assert.True(waitSignal.WaitOne(1000)); pingActor.Verify(); }
  • 12. Ping-Pong Test: Ping Actor 129 class PingActor : Actor{ int gotMessages; IMessage pongMessage; ManualResetEvent signal; const int numberOfResponsesShoulgGet = 5; public PingActor(IMessage pongMessage, ManualResetEvent signal) : base("ping") { this.signal = signal; this.pongMessage = pongMessage; MessageBus.Send(pongMessage); } public override void Handle(IMessage message) { ++gotMessages; if (numberOfResponsesShoulgGet > gotMessages) { MessageBus.Send(pongMessage); } else { signal.Set(); } } public void Verify() { Assert.AreEqual(numberOfResponsesShoulgGet, gotMessages); } }
  • 13. Ping-Pong Test: Pong Actor 130 class PongActor : Actor { IMessage pingMessage; public PongActor(IMessage pingMessage) : base("pong") { this.pingMessage = pingMessage; } public override void Handle(IMessage message) { MessageBus.Send(pingMessage); } }
  • 14. Фасад для ThreadPool 131 public interface IThreadPool { void StartTask(Action<object> task, object arg); } public class ThreadPoolImpl : IThreadPool { public void StartTask(Action<object> action, object args = null) { System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(action), args); } }
  • 15. Пример теста для ThreadPool 132 [Test] public void ThreadPoolShouldRunTasksWithArgument() { System.Threading.ManualResetEvent canContinue = new System.Threading.ManualResetEvent(false); ThreadPoolImpl pool = new ThreadPoolImpl(); object o = new object(); bool gotArgument = false; pool.StartTask((obj) => { gotArgument = object.ReferenceEquals(obj, o); canContinue.Set(); }, o); Assert.True(canContinue.WaitOne(1000)); Assert.True(gotArgument); }
  • 16. Фасад для роутера 133 public interface IRouter { void Send(IMessage message); IRouter RegisterOrReplace(string channel, Action<IMessage> handler); }
  • 17. Фасад для роутера 134 public class RouterImpl: IRouter { public RouterImpl() { routerImpl = new ConcurrentDictionary<string, Action<IMessage>>(); } public void Send(IMessage message) { Action<IMessage> handler; if (routerImpl.TryGetValue(message.Target, out handler)) { handler(message); } else { //ToDo: адресат неизвестен - надо разрешить с помощью внешнего сервиса. } } public IRouter RegisterOrReplace(string channel, Action<IMessage> handler) { routerImpl.AddOrUpdate(channel, handler, (key, oldValue) => { return handler; }); return this; } ConcurrentDictionary<string, Action<IMessage>> routerImpl; }