Example #1
0
 /// <summary>
 /// 发起消息订阅并且指定服务器端的回调函数
 /// </summary>
 ///<param name="reqSrvUrl">服务的地址,必须是Publish模式</param>
 ///<param name="resultType">服务返回的对象类型</param>
 ///<param name="action">自定义的消息处理方法</param>
 /// <param name="function">服务器的回调函数</param>
 /// <returns></returns>
 private int Subscribe(string reqSrvUrl, Type resultType, Action <string> action, MyFunc <string, string> function)
 {
     if (this.Connect())
     {
         //subServiceList.Add(new SubscribeArgs() { ReqSrvUrl = reqSrvUrl, ResultType = resultType, CallBackAction = action });
         return(ServiceSubscriber.SendMessage(reqSrvUrl, resultType, action, function, null));
     }
     else
     {
         return(0);
     }
 }
Example #2
0
 /// <summary>
 /// 以当前连接(如未打开则打开),异步请求并处理数据
 /// </summary>
 /// <typeparam name="T">请求的数据类型</typeparam>
 /// <param name="request">服务请求对象</param>
 /// <param name="resultDataType">数据类型</param>
 /// <param name="action">要异步执行的委托方法</param>
 public void RequestServiceCurrentSubscribe <T>(ServiceRequest request, DataType resultDataType, Action <T> action)
 {
     //if (sub == null || sub.Closed)
     //    throw new InvalidOperationException("未打开连接或者连接已经关闭,请先调用Connect 方法");
     CheckConnect();
     ServiceSubscriber.SendMessage(request.ServiceUrl, null, (remoteMsg) =>
     {
         //MessageConverter<T> convert = new MessageConverter<T>(remoteMsg, resultDataType);
         //if (action != null)
         //    action(convert.Result);
         // 上面代码已经优化
         ProcessRemoteMessage <T>(remoteMsg, resultDataType, null, action);
     });
 }
        private async Task <ServiceSubscriber> GetSubscriber(string path)
        {
            ServiceSubscriber result = null;
            var queryResult          = await _consul.KV.Keys(path);

            if (queryResult.Response != null)
            {
                var data = (await _consul.GetDataAsync(path));
                if (data != null)
                {
                    result = await GetSubscriber(data);
                }
            }
            return(result);
        }
Example #4
0
 /// <summary>
 /// 取消订阅,关闭连接
 /// </summary>
 public void Close()
 {
     if (ServiceSubscriber != null)
     {
         if (UseConnectionPool)
         {
             //将连接放回连接池
             PublishServicePool.Instance.BackPool(ServiceSubscriber);
         }
         else
         {
             if (!ServiceSubscriber.Closed)
             {
                 ServiceSubscriber.Close(1);
             }
         }
     }
 }
Example #5
0
        /// <summary>
        /// 以同步的方式(阻塞),获取服务执行的结果消息
        /// </summary>
        /// <typeparam name="T">消息类型</typeparam>
        /// <param name="reqSrvUrl">服务地址</param>
        /// <param name="resultDataType">消息的数据类型</param>
        /// <returns>消息转换器对象,如果不成功,返回空值</returns>
        public MessageConverter <T> GetServiceMessage <T>(string reqSrvUrl, DataType resultDataType)
        {
            CheckConnect();
            //ServiceSubscriber.SendMessage(reqSrvUrl);

            string remoteMsg = ServiceSubscriber.RequestMessage(reqSrvUrl);
            string errMsg    = ServiceConst.GetServiceErrorMessage(remoteMsg);

            if (errMsg != string.Empty)
            {
                RaiseSubscriberError(this, new MessageEventArgs(errMsg));
                return(null);
            }
            else
            {
                MessageConverter <T> convert = new MessageConverter <T>(remoteMsg, resultDataType);
                return(convert);
            }
        }
        private async Task <ServiceSubscriber> GetSubscriber(string path)
        {
            ServiceSubscriber result = null;
            var client = await _consulClientFactory.GetClient();

            var queryResult = await client.KV.Keys(path);

            if (queryResult.Response != null)
            {
                var data = await client.GetDataAsync(path);

                if (data != null)
                {
                    result = await GetSubscriber(data);
                }
            }

            return(result);
        }
Example #7
0
 /// <summary>
 /// 根据消息编号,取消当前连接订阅的服务方法,但不会关闭当前连接
 /// </summary>
 /// <param name="messageId"></param>
 public void DeSubscribe(int messageId)
 {
     //CheckConnect();
     if (ServiceSubscriber == null || ServiceSubscriber.Closed)
     {
         return;
     }
     else
     {
         if (messageId < 1)
         {
             RaiseSubscriberError(this, new MessageEventArgs("消息编号不能小于1,Number:" + messageId));
         }
         else
         {
             ServiceSubscriber.SendTextMessage(messageId, "[CMD]DeSubscribeService");
             ServiceSubscriber.RemoveMessage(messageId);
         }
     }
 }
        private async Task <ServiceSubscriber> GetSubscriber(string path)
        {
            ServiceSubscriber result = null;

            var zooKeeperClient = await _zookeeperClientProvider.GetZooKeeperClient();

            if (zooKeeperClient == null)
            {
                return(null);
            }
            if (await zooKeeperClient.ExistsAsync(path))
            {
                var data = (await zooKeeperClient.GetDataAsync(path)).ToArray();
                result = await GetSubscriber(data);

                //var watcher = nodeWatchers.GetOrDefault(path);
                //if (watcher != null)
                //{
                //    watcher.SetCurrentData(data);
                //}
            }
            return(result);
        }
Example #9
0
        static void Main(string[] args)
        {
            Console.WriteLine("Please input enter to begin.");
            Console.ReadLine();

            Console.InputEncoding  = Encoding.UTF8;
            Console.OutputEncoding = Encoding.UTF8;

            //配置客户端日志工厂
            LoggerManager.ClientLoggerFactory.AddConsole(LogLevel.Error);

            //加载配置文件
            string path       = Path.Combine(Directory.GetCurrentDirectory(), "config.json");
            var    configRoot = new ConfigurationBuilder()
                                .AddJsonFile(path)
                                .Build();

            var clientConfig = configRoot.GetClientConfig();

            var serviceProxyManager = new ServiceProxyManager();

            //创建Autofac容器并注册服务类型
            var container = GetAutofacContainer(serviceProxyManager);

            //配置服务发现
            var zookeeperConfig       = configRoot.GetZookeeperConfig();
            var zookeeperClientConfig = configRoot.GetZookeeperClientConfig();

            var serializerList = new List <ISerializer>()
            {
                new MsgPackSerializer(LoggerManager.ClientLoggerFactory),
                new ProtoBufSerializer(LoggerManager.ClientLoggerFactory)
            };

            var serviceProxyFactory = ServiceProxyCreator.CreateDefaultServiceProxyFactory(null);
            var nodeClientFactory   = NodeClientManager.CreateDefaultNodeClientFactory(zookeeperClientConfig, serializerList, LoggerManager.ClientLoggerFactory);

            var serviceSubscriber = new ServiceSubscriber(zookeeperConfig,
                                                          LoggerManager.ClientLoggerFactory,
                                                          new ServiceProxyCreator(LoggerManager.ClientLoggerFactory, serviceProxyFactory, zookeeperClientConfig.Services),
                                                          new NodeClientManager(LoggerManager.ClientLoggerFactory, nodeClientFactory))
                                    .Subscribe(container.GetNodeServiceProxyTypes())
                                    .RegistTo(serviceProxyManager);

            try
            {
                //连接服务
                serviceProxyManager.ConnectAsync().Wait();
            }
            catch (AggregateException ex)
            {
                foreach (var e in ex.InnerExceptions)
                {
                    if (e is NetworkException netEx)
                    {
                        Console.WriteLine($"Connect has net error. Host={netEx.Host}, Port={netEx.Port}, Message={netEx.Message}");
                    }
                    else
                    {
                        throw e;
                    }
                }
            }

            try
            {
                //调用服务
                var sampleService = container.Resolve <ISampleService>();
                var result        = sampleService.Welcome("XNode");
                Console.WriteLine(result);
            }
            catch (RequestTimeoutExcption ex)
            {
                Console.WriteLine($"Timeout: RequestId={ex.Request.Id}");
            }
            catch (ServiceCallException ex)
            {
                Console.WriteLine($"Service call exception: ExceptionId={ex.ExceptionId}, ExceptionMessage={ex.Message}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
            }

            Console.ReadLine();

            //关闭服务订阅
            serviceSubscriber.Dispose();

            //关闭服务连接
            serviceProxyManager.CloseAsync().Wait();

            //关闭DotNetty事件循环
            BootstrapManager.Disable();
        }
Example #10
0
        public string RequestMessage(string sendMessage)
        {
            string remoteMsg = ServiceSubscriber.RequestMessage(sendMessage);

            return(remoteMsg);
        }
Example #11
0
 /// <summary>
 /// 向服务器发送消息,当服务器处理完后,会回调当前提供的回调方法
 /// </summary>
 /// <param name="message">发给服务器的消息</param>
 /// <param name="ResultType">结果的对象类型</param>
 /// <param name="action">客户端的回调方法</param>
 /// <param name="function">在执行过程中的回调函数</param>
 /// <param name="preFunction">在执行过程前的回调函数</param>
 /// <returns>消息标识</returns>
 public int RequestService(string message, Type ResultType, Action <string> action, MyFunc <string, string> function, MyFunc <string, string> preFunction)
 {
     return(ServiceSubscriber.SendMessage(message, ResultType, action, function, preFunction));
 }