RedisBase.cs 2.84 KB
using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Threading;
using FreeRedis;
using Hh.Mes.Common.config;
using Hh.Mes.Common.log;
using Newtonsoft.Json;

namespace Hh.Mes.Common.Redis
{
    public class RedisBase
    {
        public RedisClient redisClient { get; set; }

        /// <summary>
        /// 1天
        /// </summary>
        public int dayTime = 1 * 24 * 60 * 60;

        /// <summary>
        /// 2天
        /// </summary>
        public int dayTimeTwo = 2 * 24 * 60 * 60;

        /// <summary>
        /// 20 分钟
        /// </summary>
        public int minutes20 = 20 * 60;

        public string redisIp { get; set; }

        public RedisBase()
        {
            redisIp = ConfigRead.GetInstance.GetAppsetConnection().RedisIp;
            redisClient = new RedisClient(redisIp);
        }

        public bool IsStartRedisServer()
        {
            try
            {
                redisClient.Set("projectKey", ConfigRead.GetInstance.GetAppsetConnection().LoginTitle);
                return true;
            }
            catch (Exception)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine();
                var msg = "redis server请检查服务是否开启,ip和密码是否正确 :" + ConfigRead.GetInstance.GetAppsetConnection().RedisIp;
                Console.WriteLine(msg);
                Log4NetHelper.Instance.Info(msg);
                Console.ResetColor();   
                Thread.Sleep(8000);
                return false;
            }
        }


        public bool ExistsKey(string keys)
        {
            return redisClient.Exists(keys);
        }

        public void Set(string keys, string json)
        {
            redisClient.Set(keys, json);
        }

        /// <summary>
        /// time 秒
        /// </summary>
        /// <param name="keys"></param>
        /// <param name="json"></param>
        /// <param name="time"></param>
        public void Set(string keys, string json, int time)
        {
            redisClient.Set(keys, json, time);
        }

        public void SetT<T>(string keys, T json, int time)
        {
            var val = JsonConvert.SerializeObject(json);
            redisClient.Set(keys, val, time);
        }

        public T GetT<T>(string keys)
        {
            var temp = redisClient.Get(keys);
            if (temp == null)
            {
                return default;
            }
            else
            {
                return JsonConvert.DeserializeObject<T>(temp);
            }
        }

        public string GetString(string keys)
        {
            var temp = redisClient.Get(keys);
            if (temp == null)
            {
                return default;
            }
            else
            {
                return temp;
            }
        }
    }
}