WebApi2站点部署在IIS站点上,服务器的系统版本是 Windows  Service 2019,访问量不是太大平均1秒有一次请求和返回。操作内容主要是记录数据到缓存(Redis),感觉这个压力IIS完成能承受没有问题,但是部署好经过测试后发现IIS占用的CPU开始飙升,一下了占用了50%以上,造成服务器卡顿。经过一番研究和分析,发现和Redis有关,使用的姿势不对,这个和我们平时操作关系数据库不一样,优化前写的数据封闭类TestRepository如下:

public class TestRepository
    {

        private static ConnectionMultiplexer GetMultiplexer()
        {
            string connectionString = DbConfig.RedisConnectionString;
            return ConnectionMultiplexer.Connect(connectionString); ;
        }
        public void UpdateData(DbModel model)
        {
            ConnectionMultiplexer redis = GetMultiplexer();
            var db = redis.GetDatabase(1);
            string key = GetKey(model.ID);
            db.StringSet(key, model.Json);
        }

        public string GetKey(int id){
            return string.Format("{0:000000}", id); 
        }

    }
 public class DbModel
    {
        public int ID { get; set; }

        public string Name { get; set; }

        public string Value { get; set; }

        public string Json
        {
            get
            {
                return $"{{\"{Name}\":\"{Value}\"}}";
            }

        }
    }

优化后的代码如下:

public class TestRepository
    {
        private static ConnectionMultiplexer _multiplexer=null;
        private static ConnectionMultiplexer GetMultiplexer()
        {
            if (_multiplexer == null)
            {
                string connectionString = DbConfig.RedisConnectionString;
                _multiplexer = ConnectionMultiplexer.Connect(connectionString);
            }

            return _multiplexer;
        }
        public void UpdateData(DbModel model)
        {
            ConnectionMultiplexer redis = GetMultiplexer();
            var db = redis.GetDatabase(1);
            string key = GetKey(model.ID);
            db.StringSet(key, model.Json);
        }

        public string GetKey(int id){
            return string.Format("{0:000000}", id); 
        }

    }

如此一改CPU瞬时好了很多,几乎感觉不到有程序在访问。所以问题的根源找到了吧,我使用的StackExchange.Redis 1.2.6 来操作数据库的。如果你有多个Readis操作类可以统一封装一下,共享一个ConnectionMultiplexer,这个和关系数据库中连接池不一样。
便说一下MongoDB的是不是感觉和这个很相似。

 private static MongoClient _mongoClient = null;
        private MongoClient CapMongoClient
        {
            get
            {
                if (_mongoClient == null)
                {
                    _mongoClient = new MongoClient(DbConfig.MongoSetting);
                }
                
                return _mongoClient;
            }
        }

如果有表述不对的地方欢迎指正。原创禁止转载!