1. 程式人生 > >Asp.net Core中使用Redis 來儲存Session

Asp.net Core中使用Redis 來儲存Session

今天 無意看到Asp.net Core中使用Session  ,首先要使用Session就必須新增Microsoft.AspNetCore.Session包,預設Session是隻能存去位元組,所以如果你想存取string的,那麼還的引入Microsoft.AspNetCore.Http.Extensions包,那麼在Startup.cs的ConfigureServices方法裡面新增      services.AddSession(); (在 services.AddMvc()之前),在Configure方法新增   app.UseSession(); ( app.UseMvc()之前) 這樣就可以使用Session了,預設Session是位元組方式,這裡我們使用json來序列化物件:

 public static class SessionExtensions
    {
        public static void Set(this ISession session, string key, object value)
        {
            session.SetString(key, JsonConvert.SerializeObject(value));
        }

        public static T Get<T>(this ISession session, string key)
        {
            
var value = session.GetString(key); return value == null ? default(T) : JsonConvert.DeserializeObject<T>(value); } }

使用方式:

var city = new City { ID = 1, CountryCode = "123", Name = "city", District = "District test", Population = " Population test" };
HttpContext.Session.Set("city", city);
var c2 = HttpContext.Session.Get<City>("city");

如何儲存到Redis中了?

首先需要新增對應的包Microsoft.Extensions.Caching.Redis,再呼叫AddDistributedRedisCache如下:

    public void ConfigureServices(IServiceCollection services)
        {
           // string mysqlConnectiong = Configuration.GetConnectionString("MySQL");
            string redisConnectiong = Configuration.GetConnectionString("Redis");
            services.AddSession();
            services.AddDistributedRedisCache(option=>option.Configuration=redisConnectiong);
            services.AddMvc();
        }

配置如下:

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "ConnectionStrings": {
    "MySQL": "server=localhost;port=3306;uid=root;pwd=;database=word;charset=utf8;max pool size=1000;",
    "Redis": "127.0.0.1:6379,abortConnect=false,connectRetry=3,connectTimeout=3000,defaultDatabase=1,syncTimeout=3000,version=3.2.1,responseTimeout=3000"
  }
}

這樣Session就可以儲存到Redis了。

 快取的使用也很簡單

IDistributedCache Cache;
        public ValuesController(IDistributedCache cache) {
            Cache = cache;
        }


 Cache.SetString("test", "Gavin");
            var vc = Cache.GetString("test");

我們在專案類庫如何讀配置檔案

public class ConfigurationManager
    {
        /*
         Microsoft.Extensions.Options.ConfigurationExtensions
         Microsoft.Extensions.Configuration.Abstractions
         Microsoft.AspNetCore.Http.Extensions
  Microsoft.Extensions.DependencyInjection
             */
        static IConfiguration Configuration;

        static ConfigurationManager()
        {
            var baseDir = AppContext.BaseDirectory;
             Configuration = new ConfigurationBuilder()
                .SetBasePath(baseDir)
                .Add(new JsonConfigurationSource { Path = "appsettings.json", Optional = false, ReloadOnChange = true })
                .Build();
        }

        public static T GetAppSettings<T>(string key) where T : class, new()
        {
            var appconfig = new ServiceCollection()
                .AddOptions()
                .Configure<T>( Configuration.GetSection(key))
                .BuildServiceProvider()
                .GetService<IOptions<T>>()
                .Value;
            return appconfig;
        }

    }

 public class ConnectionStrings
    {
        public string MySQL { set; get; }
        public string Redis { set; get; }
    }

單獨訪問Redis:

public class CityService
    {
        /*
         * StackExchange.Redis
         */
        static IDatabase redis;
        static object lobject = new object();
        public CityService()
        {
            if (redis == null)
            {
                lock (lobject)
                {
                    if (redis == null)
                    {
                        var connection = ConfigurationManager.GetAppSettings<ConnectionStrings>("ConnectionStrings");
                        ConnectionMultiplexer connectionMultiplexer = ConnectionMultiplexer.Connect(connection.Redis);
                        redis = connectionMultiplexer.GetDatabase();
                    }
                }
            }

        }

        public IDatabase Redis { get { return redis; } }
    }

讀取MySql

  public List<City> TestDB()
        {
            /*MySql.Data*/
            List<City> list = new List<City>();
            using (MySqlConnection con = new MySqlConnection(MySqlConnectionStr))
            {
                MySqlCommand cmd = new MySqlCommand("SELECT ID, NAME,CountryCode, District, Population FROM city ;", con);
                con.Open();
                using (MySqlDataReader reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        list.Add(new City
                        {
                            ID = reader.GetInt32("ID"),
                            Name = reader.GetString("NAME"),
                            CountryCode = reader.GetString("CountryCode"),
                            District = reader.GetString("District"),
                            Population = reader.GetString("Population")
                        });
                    }
                }
            }
            return list;
        }