/// <summary> /// 消费者开始消费消息 /// 单线程消费,减少并发冲突 /// </summary> public void Start() { while (true) { foreach (var item in _allConsumers) { foreach (var key in item.Callback.Keys) { item.Client.Send("LindQueue_Pull", SerializeMemoryHelper.SerializeToBinary(key), res => res.Buffer).ContinueWith(c => { if (c.IsFaulted) { throw c.Exception; } if (c.Result == null) { Console.WriteLine("指定topic队列为空,服务挂起15秒!"); Thread.Sleep(15000); } else { var entity = SerializeMemoryHelper.DeserializeFromBinary(c.Result) as MessageBody; item.Callback[key](entity); } }).Wait(); } } } }
public void ExecuteCommand(FastSocket.SocketBase.IConnection connection, AsyncBinaryCommandInfo commandInfo) { if (commandInfo.Buffer == null || commandInfo.Buffer.Length == 0) { Console.WriteLine("BrokenPush参数为空"); connection.BeginDisconnect(); return; } var message = SerializeMemoryHelper.DeserializeFromBinary(commandInfo.Buffer) as MessageBody; try { BrokerManager.Push(message); string result = string.Format("消息成功加入队列,Topic:{0},QueueId:{1},QueueCount:{2}", message.Topic, message.QueueId, message.QueueOffset); Console.WriteLine(result); commandInfo.Reply(connection, SerializeMemoryHelper.SerializeToBinary("OK"));//返回到客户端.. } catch (Exception) { throw; } }
/// <summary> /// 推入消息 /// </summary> /// <param name="body"></param> public PushResult Push(MessageBody body) { var result = new PushResult { PushStatus = PushStatus.Succeed }; try { _client.Send( "LindQueue_Push", SerializeMemoryHelper.SerializeToBinary(body), res => res.Buffer).ContinueWith(c => { if (c.IsFaulted) { throw c.Exception; } Console.WriteLine(SerializeMemoryHelper.DeserializeFromBinary(c.Result)); Logger.LoggerFactory.Instance.Logger_Debug("LindQueue_Push发送结果:" + Encoding.UTF8.GetString(c.Result)); }).Wait(); } catch (Exception ex) { result.PushStatus = PushStatus.Failed; result.ErrorMessage = ex.Message; } return(result); }
public void ExecuteCommand(FastSocket.SocketBase.IConnection connection, AsyncBinaryCommandInfo commandInfo) { if (commandInfo.Buffer == null || commandInfo.Buffer.Length == 0) { Console.WriteLine("BrokenPull参数为空"); connection.BeginDisconnect(); return; } var topic = SerializeMemoryHelper.DeserializeFromBinary(commandInfo.Buffer).ToString(); string topicQueueId = null; Action after = null; var offset = BrokerManager.GetConsumerQueueOffset(connection, topic, ref topicQueueId, ref after); var entity = BrokerManager.Pull(connection, topic, topicQueueId, offset); if (entity == null) { Console.WriteLine("服务端消息已被消费完!"); commandInfo.Reply(connection, null);//返回到客户端.. } else { if (after != null) { after(); } Console.WriteLine("向客户端返回消息对象:{0},IP:{1},Port:{2},connId:{3}", entity.ToString(), connection.RemoteEndPoint.Address.Address, connection.RemoteEndPoint.Port, connection.ConnectionID); commandInfo.Reply(connection, SerializeMemoryHelper.SerializeToBinary(entity));//返回到客户端.. } }
public void Insert(TEntity item) { if (item != null) { _db.HashSet(_tableName, item.Id, SerializeMemoryHelper.SerializeToJson(item)); } }
// // GET: /TestRestful/Details/5 public ActionResult Details(int id) { string body = HttpHelper.Get(UriAddress + id).Content.ReadAsStringAsync().Result; var returns = SerializeMemoryHelper.DeserializeFromJson <ResponseMessage>(body); var model = SerializeMemoryHelper.DeserializeFromJson <Models.TestApiModel>(returns.Result); return(View(model)); }
public IQueryable <TEntity> GetModel() { List <TEntity> list = new List <TEntity>(); var hashVals = _db.HashValues(_tableName).ToArray(); foreach (var item in hashVals) { list.Add(SerializeMemoryHelper.DeserializeFromJson <TEntity>(item) as TEntity); } return(list.AsQueryable()); }
public void Update(TEntity item) { if (item != null) { var old = Find(item.Id); if (old != null) { _db.HashDelete(_tableName, item.Id); _db.HashSet(_tableName, item.Id, SerializeMemoryHelper.SerializeToJson(item)); } } }
public ActionResult Index(int page = 1) { NameValueCollection nv = new NameValueCollection(); //读取资料 string body = HttpHelper.Get(UriAddress, nv) .Content.ReadAsStringAsync() .Result; var linq = SerializeMemoryHelper.DeserializeFromJson <ResponseMessage>(body); var model = (linq.Result).FromPagedListJson <Models.TestApiModel>(); return(View(model)); }
/// <summary> /// 从WEB页面发FastSocket请求 /// </summary> /// <returns></returns> public ActionResult Index() { //注册服务器节点,这里可注册多个(name不能重复) var client = new DSSBinarySocketClient(8192, 8192, 3000, 3000); client.RegisterServerNode("127.0.0.1:8403", new System.Net.IPEndPoint(System.Net.IPAddress.Parse("127.0.0.1"), 8403)); client.Send("UserInsert", 1, "zzl", 1, "test", SerializeMemoryHelper.SerializeToBinary("hello web world!"), res => res.Buffer).ContinueWith(c => { if (c.IsFaulted) { throw c.Exception; } Console.WriteLine(Encoding.UTF8.GetString(c.Result)); }); ViewBag.msg = "消息发送了"; return(View()); }
/// <summary> /// 执行命令并返回结果 /// </summary> /// <param name="connection"></param> /// <param name="commandInfo"></param> public void ExecuteCommand(IConnection connection, DSSBinaryCommandInfo commandInfo) { if (commandInfo.Buffer == null || commandInfo.Buffer.Length == 0) { Console.WriteLine("UserInsert参数为空"); connection.BeginDisconnect(); return; } var entity = SerializeMemoryHelper.DeserializeFromBinary(commandInfo.Buffer); string str = "result:1,versonNumber:" + commandInfo.VersionNumber + ",extProperty:" + commandInfo.ExtProperty + ",projectName:" + commandInfo.ProjectName + ",message:" + entity.ToString(); Console.WriteLine(str); commandInfo.Reply(connection, Encoding.UTF8.GetBytes(str));//返回到客户端... }
/// <summary> /// 直接为APP返回的支付字符串 /// </summary> /// <param name="orderId"></param> /// <param name="subject"></param> /// <param name="total_fee"></param> /// <returns></returns> public string AppPayFormString(string orderNo, decimal totalFee, string subject = null, string body = "Lind") { //必填,不需要修改 Random random = new Random(System.Environment.TickCount); //请求号 string req_id = string.IsNullOrWhiteSpace(orderNo) ? DateTime.Now.ToString("yyyyMMddHHmmss") + random.Next(10000, 99999) : orderNo; SortedDictionary <string, object> sParaTemp = new SortedDictionary <string, object>(); AliPayBussiness bussin = new AliPayBussiness() { timeout_express = "10m", seller_id = Config.AlipayConfig.Partner, product_code = "QUICK_MSECURITY_PAY", total_amount = totalFee.ToString("0.00"), subject = subject, body = body, out_trade_no = orderNo, }; sParaTemp.Add("app_id", Config.AlipayConfig.AppId); string bizcont = SerializeMemoryHelper.SerializeToJson <AliPayBussiness>(bussin); sParaTemp.Add("biz_content", bizcont); sParaTemp.Add("charset", Config.Input_charset); sParaTemp.Add("method", "alipay.trade.app.pay"); sParaTemp.Add("format", "json"); sParaTemp.Add("sign_type", Config.AlipayConfig.Sign_type); //这个单拿出来,和sign拼到最后 sParaTemp.Add("timestamp", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); sParaTemp.Add("version", "1.0"); sParaTemp.Add("notify_url", Config.AlipayConfig.Notify_url); //生成Url string content = sParaTemp.ToUrl(); //生成签名 string sign = RSAFromPkcs8.sign(content, Config.AlipayConfig.Private_key, Config.AlipayConfig.Input_charset); //追加签名 content += "&sign=" + sign; //整个字符做UrlEncode content = RSAFromPkcs8.EncodeEx(content); Lind.DDD.Logger.LoggerFactory.Instance.Logger_Info("向APP返回的字符串包括Sign:" + content); return(content); }
public void ExecuteCommand(IConnection connection, AsyncBinaryCommandInfo commandInfo) { if (commandInfo.Buffer == null || commandInfo.Buffer.Length == 0) { Console.WriteLine("SendQueue参数为空"); connection.BeginDisconnect(); return; } var entity = SerializeMemoryHelper.DeserializeFromBinary(commandInfo.Buffer); string str = "result:1,CmdName:" + commandInfo.CmdName + ",SeqID:" + commandInfo.SeqID + ",message:" + entity.ToString(); Console.WriteLine(str); var old = new User { Name = "hello world" }; commandInfo.Reply(connection, SerializeMemoryHelper.SerializeToBinary(old));//返回到客户端.. }
public TEntity Find(params object[] id) { return(SerializeMemoryHelper.DeserializeFromJson <TEntity>(_db.HashGet(_tableName, (string)id[0])) as TEntity); }
/// <summary> /// 出队列JSON /// </summary> /// <param name="cache"></param> /// <param name="key"></param> /// <returns></returns> public static void PushJson <T>(this IDatabase cache, string key, T obj) { cache.ListRightPush(key, SerializeMemoryHelper.SerializeToJson <T>(obj)); }
/// <summary> /// 出队列JSON /// </summary> /// <typeparam name="T"></typeparam> /// <param name="cache"></param> /// <param name="key"></param> /// <returns></returns> public static T PopJson <T>(this IDatabase cache, string key) { return(SerializeMemoryHelper.DeserializeFromJson <T>(cache.ListLeftPop(key))); }
/// <summary> /// 得到键所对应的值 /// </summary> /// <param name="cache"></param> /// <param name="key"></param> /// <returns></returns> public static object Get(this IDatabase cache, string key) { return(SerializeMemoryHelper.DeserializeFromJson <object>(cache.StringGet(key))); }
public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext) { var responseDataSegment = new ResponseDataSegment(); var context = (HttpContextBase)actionContext.Request.Properties["MS_HttpContext"]; //获取传统context var Request = context.Request; //定义传统request对象 var query = Request.QueryString["dataSeg"]; RequestDataSegment data = new RequestDataSegment(); if (query != null) { data = SerializeMemoryHelper.DeserializeFromJson <RequestDataSegment>(query); } if (data != null && data.RequestData.Any()) { foreach (var item in data.RequestData) { try { HttpResponseMessage response; var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip }; using (var http = new HttpClient(handler)) { if (item.HttpMethod == 0) { if (item.RequestParam != null) { item.Url += "?"; foreach (var p in item.RequestParam) { item.Url += p.Key + "=" + p.Value + "&"; } item.Url = item.Url.Remove(item.Url.Length - 1, 1); } response = http.GetAsync(item.Url).Result; } else { var content = new FormUrlEncodedContent(item.RequestParam); response = http.PostAsync(item.Url, content).Result; } response.EnsureSuccessStatusCode(); responseDataSegment.ResponseData.Add(new ResponseMessage { GuidKey = item.GuidKey, Status = 200, Result = response.Content.ReadAsStringAsync().Result }); } } catch (Exception ex) { responseDataSegment.ResponseData.Add(new ResponseMessage { GuidKey = item.GuidKey, Status = 100, Result = ex.Message }); } } } actionContext.Response = new HttpResponseMessage { Content = new StringContent(SerializeMemoryHelper.SerializeToJson(responseDataSegment), Encoding.GetEncoding("UTF-8"), "application/json") }; base.OnActionExecuting(actionContext); }
/// <summary> /// 设置键对应的值,过期时间后自己删除 /// </summary> /// <param name="cache"></param> /// <param name="key"></param> /// <param name="value"></param> /// <param name="expireMinutes"></param> public static void Set(this IDatabase cache, string key, object value, int expireMinutes) { string json = SerializeMemoryHelper.SerializeToJson(value); cache.StringSet(key, json, TimeSpan.FromMinutes(expireMinutes)); }
public static void Append(this IDatabase cache, string key, object value) { string json = SerializeMemoryHelper.SerializeToJson(value); cache.StringAppend(key, json); }
/// <summary> /// 方法拦截 /// </summary> /// <param name="actionContext"></param> public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext) { #region 例外 bool skipAuthorization = actionContext.ControllerContext.ControllerDescriptor.ControllerType.IsDefined(typeof(AllowAnonymousAttribute), inherit: true) || actionContext.ControllerContext.ControllerDescriptor.ControllerType.IsDefined(typeof(AllowAnonymousAttribute), inherit: true); if (skipAuthorization) { return; } #endregion #region 初始化 var context = (HttpContextBase)actionContext.Request.Properties["MS_HttpContext"]; //获取传统context var request = context.Request; //定义传统request对象 var paramStr = new StringBuilder(); //校验码只从Url地址后取,不从表单取 var coll = new NameValueCollection(request.QueryString); coll.Add(request.Form); //StringContent方式的提交 //var task = actionContext.Request.Content.ReadAsByteArrayAsync().Result; //var result = Encoding.UTF8.GetString(task); //if (!string.IsNullOrWhiteSpace(result)) //{ // foreach (var key in result.FromJson().Keys) // coll.Add(key, (string)result.FromJson()[key]); //} #endregion #region 解析XML配置文件 var config = CacheConfigFile.ConfigFactory.Instance.GetConfig <ApiValidateModelConfig>() .ApiValidateModelList .FirstOrDefault(i => i.AppKey == coll["AppKey"]); if (config == null) { actionContext.Response = new HttpResponseMessage(HttpStatusCode.Forbidden) { Content = new StringContent(SerializeMemoryHelper.SerializeToJson(new ResponseMessage() { Status = 0, ErrorCode = "001", ErrorMessage = "AppKey不是合法的,请先去组织生成有效的Key" })) }; base.OnActionExecuting(actionContext); return; } if (config.ExpireDate < DateTime.Now) { actionContext.Response = new HttpResponseMessage(HttpStatusCode.Forbidden) { Content = new StringContent(SerializeMemoryHelper.SerializeToJson(new ResponseMessage() { Status = 0, ErrorCode = "002", ErrorMessage = "AppKey不是合法的,密钥已过期" })) }; base.OnActionExecuting(actionContext); return; } #endregion #region 验证算法 var keys = new List <string>(); foreach (string param in coll.Keys) { if (!string.IsNullOrEmpty(param)) { keys.Add(param.ToLower()); } } keys.Sort(); foreach (string p in keys) { if (p != ApiValidateHelper.CipherText) { if (!string.IsNullOrEmpty(coll[p])) { paramStr.Append(coll[p]); } } } paramStr.Append(config.PassKey); #endregion double timeStamp; if (double.TryParse(coll["timeStamp"], out timeStamp)) { //当前UTC时间与1700/01/01的时间戳 if (((DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds - timeStamp) / 60 > config.ValidateMinutes) { actionContext.Response = new HttpResponseMessage(HttpStatusCode.Forbidden) { Content = new StringContent(SerializeMemoryHelper.SerializeToJson(new ResponseMessage() { Status = 0, ErrorCode = "003", ErrorMessage = "请求已过期" })) }; } } else { actionContext.Response = new HttpResponseMessage(HttpStatusCode.Forbidden) { Content = new StringContent(SerializeMemoryHelper.SerializeToJson(new ResponseMessage() { Status = 0, ErrorCode = "003", ErrorMessage = "时间戳异常" })) }; } if (Lind.DDD.Utils.Encryptor.Utility.EncryptString(paramStr.ToString(), Lind.DDD.Utils.Encryptor.Utility.EncryptorType.MD5) != coll[ApiValidateHelper.CipherText]) { actionContext.Response = new HttpResponseMessage(HttpStatusCode.Forbidden) { Content = new StringContent(SerializeMemoryHelper.SerializeToJson(new ResponseMessage() { Status = 0, ErrorCode = "003", ErrorMessage = "验证失败,请求非法" })) }; } base.OnActionExecuting(actionContext); }