• 提高WCF的吞吐效率


    1 using System;
    2 using System.Collections.Generic;
    3 using System.IO;
    4 using System.IO.Compression;
    5 using System.Linq;
    6 using System.Text;
    7 using System.Runtime.Serialization.Formatters.Binary;
    8
    9 namespace Kingge.Mini.Network
    10 {
    11 /// <summary>
    12 /// 压缩工具类,可以用于减小流量,提升传输效率
    13 /// </summary>
    14 public static class DeflateUtil
    15 {
    16 /// <summary>
    17 /// 还原对象信息
    18 /// </summary>
    19 /// <param name="bytes">字节数组</param>
    20 public static object GetObject(byte[] bytes)
    21 {
    22 if (bytes==null||bytes.Length==0)
    23 {
    24 return null;
    25 }
    26 using (MemoryStream memory=new MemoryStream(bytes))
    27 {
    28 int first=memory.ReadByte();
    29 //判断标记位,0直接还原,1先解压再还原
    30 if (first == 0)
    31 {
    32 BinaryFormatter formatter = new BinaryFormatter();
    33 return formatter.Deserialize(memory);
    34 }
    35 else
    36 {
    37 using (DeflateStream deflate=new DeflateStream(memory,CompressionMode.Decompress,true))
    38 {
    39 BinaryFormatter formatter = new BinaryFormatter();
    40 return formatter.Deserialize(deflate);
    41 }
    42 }
    43 }
    44 }
    45
    46 /// <summary>
    47 /// 压缩对象
    48 /// </summary>
    49 /// <param name="obj">被压缩对象</param>
    50 public static byte[] DeflateObject(object obj)
    51 {
    52 if (obj==null)
    53 {
    54 return null;
    55 }
    56 //值类型或者字符串没有压缩的必要
    57 if (obj.GetType().IsValueType||obj is string)
    58 {
    59 using (MemoryStream memory=new MemoryStream())
    60 {
    61 //写入标记位0,表示未经过压缩
    62 memory.WriteByte((byte)0);
    63 BinaryFormatter formatter = new BinaryFormatter();
    64 formatter.Serialize(memory,obj);
    65 memory.Position = 0;
    66 return memory.ToArray();
    67 }
    68 }
    69 else
    70 {
    71 using (MemoryStream memory = new MemoryStream())
    72 {
    73 //写入标记位1,表示经过压缩
    74 memory.WriteByte((byte)1);
    75 using (DeflateStream deflate=new DeflateStream(memory,CompressionMode.Compress,true))
    76 {
    77 BinaryFormatter formatter = new BinaryFormatter();
    78 formatter.Serialize(deflate, obj);
    79 }
    80 memory.Position = 0;
    81 return memory.ToArray();
    82 }
    83 }
    84 }
    85 }
    86 }
  • 相关阅读:
    springcloud的turbine集成zookeeper
    点赞功能与redis的相遇
    kmeans聚类源代码
    java map.entry
    M2Eclipse:Maven Eclipse插件无法搜索远程库的解决方法
    Maven仓库
    java生成验证码
    手工利用Chrome浏览器“Javascript控制台”
    分类算法之朴素贝叶斯分类(Naive Bayesian classification)
    JavaWeb 服务启动时,在后台启动加载一个线程
  • 原文地址:https://www.cnblogs.com/kingge/p/2040876.html
Copyright © 2020-2023  润新知