using ServiceStack.Redis;
using System;
using System.Collections.Generic;
using System.Text;

namespace WsSubDemoNetCore
{
    /// <summary>
    /// 使用Redis作为存储数据库
    /// </summary>
    public class RedisOutObj
    {
        public PooledRedisClientManager PooledClientManager { get; set; }


        public RedisOutObj(string server, int writepoosize = 10, int readpoolsize = 10, int db = 0)
        {
            var config = new RedisClientManagerConfig
            {
                AutoStart = true,
                MaxWritePoolSize = writepoosize,
                MaxReadPoolSize = readpoolsize,
                DefaultDb = db
            };

            PooledClientManager = new PooledRedisClientManager(new string[] { server }, new string[] { server }, config)
            {
                ConnectTimeout = 3000,
                SocketSendTimeout = 1500,
                SocketReceiveTimeout = 1500
            };
        }

        public RedisClient GetRedisClient()
        {
            return PooledClientManager.GetClient() as RedisClient;
        }

		/// <summary>
		/// 存储键值类数据
		/// </summary>
		/// <param name="key"></param>
		/// <param name="value"></param>
		/// <param name="expirySeconds"></param>
		public void SetItem(string key, string value, int expirySeconds = -1)
        {
            RedisClient redisClient = GetRedisClient();
            try
            {
                if (expirySeconds <= 0)
                {
                    redisClient.Set(key, value);
                }
                else
                {
                    redisClient.Set(key, value, new TimeSpan(0, 0, 0, expirySeconds));
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                redisClient.Dispose();
            }
        }

        /// <summary>
        /// 存储列表类数据
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="score"></param>
		public void SetSortList(string key, string value, long score)
		{
			RedisClient redisClient = GetRedisClient();
			try
			{
                redisClient.AddItemToSortedSet(key,value,score);
			}
			catch
			{
				throw;
			}
			finally
			{
				redisClient.Dispose();
			}
		}

		public string GetValue(string key)
        {
            RedisClient redisClient = GetRedisClient();
            try
            {
                return redisClient.GetValue(key);
            }
            catch
            {
                throw;
            }
            finally
            {
                redisClient.Dispose();
            }
        }
    }
}
