1 module hunt.service.remoting.invoker.ServiceInvokerFactory;
2 
3 import grpc;
4 
5 import hunt.collection.HashMap;
6 import hunt.collection.Map;
7 import hunt.logging;
8 
9 import hunt.service.util.UrlHelper;
10 import hunt.service.util.UrlInfo;
11 import hunt.service.RegistryConfig;
12 
13 import neton.client.NetonFactory;
14 import neton.client.registry.RegistryService;
15 import neton.client.NetonOption;
16 import neton.client.registry.Instance;
17 import neton.client.Listener;
18 import neton.client.Event;
19 
20 import std.random;
21 
22 public class ServiceInvokerFactory
23 {
24 
25 	private
26 	{
27 		RegistryService _register;
28 		Instance[][string] _services;
29 		NetonOption _neton;
30 		bool _useRegistry = false;
31 		RegistryConfig _registryConf;
32 		UrlInfo _urlInfo;
33 	}
34 
35 	this()
36 	{
37 	}
38 
39 	T createClient(T)()
40 	{
41 		if (_useRegistry)
42 		{
43 			if (_registryConf.serviceName in _services)
44 			{
45 				auto instances = _services[_registryConf.serviceName];
46 				if (instances.length > 0)
47 				{
48 					auto idx = uniform(0, instances.length);
49 					logInfof("random ip : %s , port : %d ", instances[idx].ip, instances[idx].port);
50 					auto channel = new GrpcClient(instances[idx].ip, instances[idx].port);
51 					return new T(channel);
52 				}
53 			}
54 		}
55 		else
56 		{
57 			auto channel = new GrpcClient(_urlInfo.getHost(), cast(ushort)(_urlInfo.getPort()));
58 			return new T(channel);
59 		}
60 
61 		return null;
62 	}
63 
64 	void setDirectUrl(string url)
65 	{
66 		_useRegistry = false;
67 		_urlInfo = new UrlInfo;
68 		_urlInfo = UrlHelper.toProviderInfo(url);
69 	}
70 
71 	void setRegistry(RegistryConfig conf)
72 	{
73 		_useRegistry = true;
74 		_registryConf = conf;
75 		_neton.ip = conf.ip;
76 		_neton.port = conf.port;
77 		_register = NetonFactory.createRegistryService(_neton);
78 
79 		if (!(conf.serviceName in _services))
80 		{
81 			//dfmt off
82 			_register.subscribe(conf.serviceName, new class Listener
83 				{
84 					override void onEvent(Event event)
85 					{
86 						logInfo("service listen : ", event); 
87 						_services[conf.serviceName] = _register.getAllInstances(conf.serviceName);
88 					}
89 				}
90 				);
91 			//dfmt on
92 			auto instances = _register.getAllInstances(conf.serviceName);
93 			_services[conf.serviceName] = instances;
94 			logInfo("invoker service : ", conf.serviceName, " all instance :", instances);
95 		}
96 	}
97 }