Asp.net Core中使用Redis 来保存Session, 读取配置文件
2017-06-21 18:34
1416 查看
今天 无意看到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来序列化对象:
使用方式:
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如下:
配置如下:
这样Session就可以保存到Redis了。
缓存的使用也很简单
我们在项目类库如何读配置文件
单独访问Redis:
读取MySql
参考 ASP.NET Core实现类库项目读取配置文件
ASP.NET Core实现强类型Configuration读取配置数据
4.3 可配置的分布式缓存(上)
Asp.net Core 使用Redis存储Session
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; }
参考 ASP.NET Core实现类库项目读取配置文件
ASP.NET Core实现强类型Configuration读取配置数据
4.3 可配置的分布式缓存(上)
Asp.net Core 使用Redis存储Session
相关文章推荐
- IT咨询顾问:一次吐血的项目救火 java或判断优化小技巧 asp.net core Session的测试使用心得 【.NET架构】BIM软件架构02:Web管控平台后台架构 NetCore入门篇:(十一)NetCore项目读取配置文件appsettings.json 使用LINQ生成Where的SQL语句 js_jquery_创建cookie有效期问题_时区问题
- 菜鸟入门【ASP.NET Core】5:命令行配置、Json文件配置、Bind读取配置到C#实例、在Core Mvc中使用Options
- 【ASP.NET Core快速入门】(五)命令行配置、Json文件配置、Bind读取配置到C#实例、在Core Mvc中使用Options
- Asp.net Core中使用Redis 来保存Session
- Asp.Net Core 集成 Hangfire 配置使用 Redis 存储
- ASP.NET Core实现类库项目读取配置文件
- ASP.NET Core实现类库项目读取配置文件
- ASP.NET Core实现类库项目读取配置文件
- 【无私分享:ASP.NET CORE 项目实战(第六章)】读取配置文件(一) appsettings.json
- 【无私分享:ASP.NET CORE 项目实战(第八章)】读取配置文件(二) 读取自定义配置文件
- ASP.NET Core 使用Redis存储Session
- [转]Asp.net Core 使用Redis存储Session
- Asp.net Session保存到Redis: 使用 RedisSessionStateProvider
- ASP.NET Core 使用 Redis 和 Protobuf 进行 Session 缓存
- IIS部署ASP.NET网站后提示只有在配置文件或 Page 指令中将 enableSessionState 设置为 true 时,才能使用会话状态...
- 如何在ASP.NET Core类库项目中读取配置文件详解
- Asp.net Core 使用Redis存储Session
- 详解Asp.net Core 使用Redis存储Session
- 【无私分享:ASP.NET CORE 项目实战(第六章)】读取配置文件(一) appsettings.json
- Asp.net Session保存到Redis 使用 RedisSessionStateProvider报错