首页 > 其他分享 >7.读写配置文件和添加缓存

7.读写配置文件和添加缓存

时间:2024-02-10 09:11:19浏览次数:32  
标签:缓存 string 配置文件 读写 private value key public

感觉没什么好总结的,直接上代码吧:

配置文件:

1添加一个枚举

/// <summary>
    /// 配置键名
    /// </summary>
    public enum ConfigKey
    {
        /// <summary>
        /// 系统配置
        /// </summary>
        SystemConfig,

        /// <summary>
        /// 缓存配置
        /// </summary>
        CacheConfig,
    }

2.添加一个读写的接口

/// <summary>
    /// 配置管理器接口
    /// </summary>
    public interface IConfigManager
    {
        /// <summary>
        /// 读取本地配置
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        T Read<T>(ValueType key);

        /// <summary>
        /// 保存配置到本地
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="value"></param>
        void Write<T>(ValueType key, T value);
    }

3.实现该接口

 /// <summary>
    /// 读写配置文件
    /// </summary>
    [ExposedService(Lifetime.Singleton, typeof(IConfigManager))]
    public class ConfigManager : IConfigManager
    {
        private const string root = "Config";
        private string GetFullPath(ValueType key)
        {
            return Path.Combine(root, key.GetType().FullName + "." + key.ToString() + ".json");
        }

        /// <summary>
        /// 读配置文件
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        public T Read<T>(ValueType key)
        {
            string filename = GetFullPath(key);
            return JsonHelper.Load<T>(filename);
        }

        /// <summary>
        /// 写配置文件
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public void Write<T>(ValueType key, T value)
        {
            Assert.NotNull(key);
            Assert.NotNull(value);
            Directory.CreateDirectory(root);
            string filename = GetFullPath(key);
            JsonHelper.Save(value, filename, true);
        }
    }

 

缓存:

1.添加一个枚举

 /// <summary>
    /// 用枚举区分缓存
    /// </summary>
    public enum CacheKey
    {
        /// <summary>
        /// 当前用户
        /// </summary>
        User,

        /// <summary>
        /// 是否自动登录 
        /// </summary>
        IsAutoLogin,

        /// <summary>
        /// 是否记住密码
        /// </summary>
        IsRemember,

        /// <summary>
        /// 缓存数据
        /// </summary>
        AppData,
        /// <summary>
        /// 过滤器算法缓存数据
        /// </summary>
        Filters,
    }

2.添加一个接口

/// <summary>
    /// 缓存接口
    /// </summary>
    public interface ICacheManager
    {
        /// <summary>
        /// 获取缓存
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        bool Get<T>(ValueType key, out T value);

        /// <summary>
        /// 保存缓存
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="value"></param>
        void Set<T>(ValueType key, T value);

        /// <summary>
        /// 删存缓存
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        void Delete(ValueType key);
    }

3.josn帮助类 需要添加Newtonsoft.Json

 /// <summary>
    /// Json文件的序列化和反序列化帮助类
    /// </summary>
    public static class JsonHelper
    {
        /// <summary>
        /// 加载某个JSON文件并返回指定的类型实例
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static T Load<T>(string fileName)
        {
            if (!File.Exists(fileName))
            {
                return default(T);
            }

            string content = File.ReadAllText(fileName);
            return Deserialize<T>(content);
        }

        public static T Deserialize<T>(string content)
        {
            return JsonConvert.DeserializeObject<T>(content);
        }

        /// <summary>
        /// 将指定的类型实例保存为JSON文件
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="fileName"></param>
        /// <param name="indented"></param>
        public static void Save(object obj, string fileName, bool indented = false)
        {
            string content = Serialize(obj, indented);
            File.WriteAllText(fileName, content);
        }

        public static string Serialize(object obj, bool indented = false)
        {
            Formatting formatting = indented ? Formatting.Indented : Formatting.None;
            return JsonConvert.SerializeObject(obj, formatting);
        }

    }

 

4.实现该缓存接口

/// <summary>
    /// 提供缓存服务的管理器
    /// </summary>
    [ExposedService(Lifetime.Singleton, typeof(ICacheManager))]
    class CacheManager : ICacheManager
    {
        private IConfigManager configManager;//读写配置文件
        private Dictionary<string, string> cacheNames;
        private readonly object cacheLock = new object();
        public CacheManager(IConfigManager configManager)
        {
            this.configManager = configManager;
            cacheNames = configManager.Read<Dictionary<string, string>>(ConfigKey.CacheConfig) ?? new Dictionary<string, string>();
        }


        /// <summary>
        /// 获取本地缓存内容
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public bool Get<T>(ValueType key, out T value)
        {
            value = default(T);
            string obj = key.ToString();
            lock (cacheLock)
            {
                if (!cacheNames.ContainsKey(key.GetFullName()))
                    return false;
                obj = cacheNames[key.GetFullName()];
            }

            try
            {
                value = JsonHelper.Deserialize<T>(obj);
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        public void Set<T>(ValueType key, T value)
        {
            Assert.NotNull(key);
            Assert.NotNull(value);

            string content = JsonHelper.Serialize(value);

            lock (cacheLock)
            {
                if (cacheNames.ContainsKey(key.GetFullName()))
                {
                    //若存在则修改
                    cacheNames[key.GetFullName()] = content;
                }
                else
                {
                    cacheNames.Add(key.GetFullName(), content);
                }

                configManager.Write(ConfigKey.CacheConfig, cacheNames);

            }
        }

        /// <summary>
        /// 删除缓存内容
        /// </summary>
        /// <param name="key"></param>
        public void Delete(ValueType key)
        {
            lock (cacheLock)
            {
                if (cacheNames.ContainsKey(key.GetFullName()))
                {
                    cacheNames.Remove(key.GetFullName());
                    configManager.Write(ConfigKey.CacheConfig, cacheNames);
                }
            }
        }
    }

 

使用:

拿登录来说

public class LoginViewModel : BindableBase
    {

        private UserInfo userInfoModel;
        public UserInfo UserInfoModel
        {
            get { return userInfoModel; }
            set { userInfoModel = value; RaisePropertyChanged(); }
        }

        private bool isRemember;
        /// <summary>
        /// 是否记住密码
        /// </summary>
        public bool IsRemember
        {
            get { return isRemember; }
            set { isRemember = value; RaisePropertyChanged(); }
        }

        private bool isAutoLogin;
        /// <summary>
        /// 是否自动登录
        /// </summary>
        public bool IsAutoLogin
        {
            get { return isAutoLogin; }
            set { isAutoLogin = value; RaisePropertyChanged(); }
        }



        private ICacheManager _CacheManager { get; }
        public IRegionManager _regionManager { get; private set; }
        public IEventAggregator _eventAggregator { get; private set; }

        public ICacheHelper _cacheHelper { get; private set; }//缓存

        public IUserInfoService _userInfoService { get; private set; }

        public DelegateCommand LoginCommand { get; private set; }

        public LoginViewModel(IRegionManager regionManager, IEventAggregator eventAggregator,
            ICacheHelper cacheHelper, IUserInfoService userInfoService, ICacheManager cacheManager)
        {
            UserInfoModel = new UserInfo();
            _regionManager = regionManager;
            _eventAggregator = eventAggregator;
            _cacheHelper = cacheHelper;
            _userInfoService = userInfoService;
            _cacheHelper = new MemoryCacheHelper();
            _CacheManager = cacheManager;
            LoginCommand = new DelegateCommand(UserLogin);

            LoadUserCache();

            //是否自动登录 
            Task.Delay(2000).ContinueWith(t =>
            {
                //如果自动登录
                if (IsAutoLogin)
                {
                    LoginCommand.Execute();//执行登录
                }
            });
        }


       

        private void UserLogin()
        {
            if (string.IsNullOrEmpty(UserInfoModel.UserName) || string.IsNullOrEmpty(UserInfoModel.PassWord))
                return;

            //如果记住密码
            if (IsRemember)
            {
                _CacheManager.Set(CacheKey.User, UserInfoModel);//写入缓存
            }
            else
            {
                _CacheManager.Delete(CacheKey.User);//删除缓存
            }

            _CacheManager.Set(CacheKey.IsRemember, IsRemember);//记住密码写入缓存
            _CacheManager.Set(CacheKey.IsAutoLogin, IsAutoLogin);//自动登录写入缓存


            if (UserInfoModel.UserName == "老六" && UserInfoModel.PassWord == "123456")
            {
                //UserInfoModel.PassWord = UserInfoModel.PassWord.GetMD5();
                //var resu = _userInfoService.Login(UserInfoModel);
                //if (resu.Code == MyResponseCode.Success)
                //{
                //    var userInfo = JsonConvert.DeserializeObject<UserInfo>(resu.Data.ToString());
                //    _cacheHelper.Set<string>("token", userInfo.Remark);//token存到缓存中
                //    _eventAggregator.SendMessager(ViewNames.LoginView, "登入成功");//发布
                //}
                //else
                //{
                //    PopupBox.Show("登录失败,API接口返回失败");
                //}
                _eventAggregator.SendMessager(ViewNames.LoginView, "登入成功");//发布
            }
            else
            {
                PopupBox.Show("用户名或密码错误");
            }
        }

        /// <summary>
        /// 获取用户缓存
        /// </summary>
        private void LoadUserCache()
        {
            if (_CacheManager.Get(CacheKey.User, out UserInfo user))
            {
                UserInfoModel.UserName = user.UserName;
                UserInfoModel.PassWord = user.PassWord;
            }

            if (_CacheManager.Get(CacheKey.IsRemember, out bool isRemember))
            {
                IsRemember = isRemember;
            }

            if (_CacheManager.Get(CacheKey.IsAutoLogin, out bool isAutoLogin))
            {
                IsAutoLogin = isAutoLogin;
            }
        }
    }

 

标签:缓存,string,配置文件,读写,private,value,key,public
From: https://www.cnblogs.com/MingQiu/p/18012741

相关文章

  • MyBatis缓存
    MyBatis缓存缓存就是内存中的数据,常常来自对数据库查询结果的保存,使用缓存,我们可以避免频繁的与数据进行交互,进而提高响应速度。MyBatis也提供两种缓存模式,分为一级缓存和二级缓存。优点:提供查询效率减少频繁进行I/O操作,从而减少数据库的压力。适合存放缓存的数据:【1】查询频......
  • Windows查看删除DNS缓存
    Windows查看删除DNS缓存查看DNS缓存查看所有DNS缓存打开CMD,输入ipconfig/displaydns​C:\>ipconfig/displaydnsWindowsIP配置github.dev----------------------------------------记录名称.......:github.dev记录类型.......:1生存时间.............
  • Etcd读写性能测试
    单节点etcd集群,etcd版本是3.4.9。编译etcdbenchmarkgitclonehttps://github.com/etcd-io/etcd.gitcdetcd/gitcheckoutv3.4.9rm-rfvendorgoinstall-v./tools/benchmarkgolist-f"{{.Target}}"./tools/benchmark写入测试KeyENDPOINTS=https://192.168.3.14:2......
  • H3C 设备配置文件备份还原实验
    H3C设备配置文件备份还原实验H3C模拟器搭建实验,仅为参考(2024年1月14日)实验拓扑实验需求1、按照图示连接到真机,并配置IP地址(真机IP地址配置到VirtualBoxHost-OnlyEthernetAdapter网卡)2、R1保存当前配置3、在R1上开启FTP服务4、使用真机访问FTP服务,把R1的配置文件拷......
  • H3C 设备配置文件备份还原实验
    H3C设备配置文件备份还原实验H3C模拟器搭建实验,仅为参考(2024年1月14日)实验拓扑实验需求1、按照图示连接到真机,并配置IP地址(真机IP地址配置到VirtualBoxHost-OnlyEthernetAdapter网卡)2、R1保存当前配置3、在R1上开启FTP服务4、使用真机访问FTP服务,把R1的配置文件拷......
  • Spring 缓存失效经验
    Spring缓存失效经验基础背景Spring通过代理+切面的方式增强方法实现的声明式缓存,事务等的支持通用失效场景方法调用为内部调用方法未声明为public方法笔者失效场景key值获取结果不一致。笔者代码如下所示,方法入参是一个包装对象,缓存key采用方法名+对象的json......
  • Mybatis 的 SqlSession 和一级缓存为什么失效?
    目录SqlSession是什么SqlSession分类SqlSession的创建为什么和Spring整合后的SqlSession一级缓存偶尔会失效一级缓存和二级缓存总结SqlSession是什么SqlSession是Mybatis中定义的,用来表示与关系数据库的一次会话,会话定义了各种具体的操作,查询、数据更新(包含保存、更新、删......
  • Nginx--安装&&配置文件
    官网:http://nginx.org/en/download.htmlnginx版本:1.18一 安装1下载预编译环境(预编译报错需要安装什么库直接在库名后面接-devel 使用yum下载)yum-yinstallpcre-developenssl-develgccgcc-c++2 创建用户,解压包useradd-M-r-s/sbin/nologinnginxtarxvfnginx-1.......
  • Nginx--缓存
    一般存的是静态资源,可以提高客户端的访问速度,并减轻服务器的压力 1 客户端缓存通过设置expires指令,响应头中将会返回Expires和Cache-Control字段当浏览器发现响应头存在这样的缓存字段,当再次请求相同资源时,就会确认在客户端的资源是否过期location/{expires30m......
  • Nginx--引用多配置文件
    在nginx.conf的http模块,include指定某个目录下的*.confusernginx;worker_processesauto;error_log/var/log/nginx/error.log;pid/run/nginx.pid;#Loaddynamicmodules.See/usr/share/nginx/README.dynamic.include/usr/share/nginx/modules/*.conf;events{......