Redis可以用來存儲session或直接存儲鍵值對
首先要有asp.net core的項目,可以是webapi 或者MVC項目,
還有有本地的Redis或者在遠程服務器上,具體的安裝就不講述了 以下是具體配置過程:
1.安裝 "Microsoft.Extensions.Caching.Redis.Core": "1.0.3"(版本根據自己的好項目的需求自行選擇,本次以1.0.3為例展示)
2.配置startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddDistributedRedisCache(options =>
{
options.InstanceName = "Session:";
options.Configuration = Configuration.GetConnectionString("Redis");// "139.196.228.246:6379,password=eland2swzl,defaultdatabase=1";//
});
}
defaultdatabase 定義了數據保存的位置 1 就是默認載db1中
InstanceName 定義了添加的數據所在的文件路徑以及前綴,“:”是層次的分隔符,比如“school:class:student_” 添加的數據("name":"zhangsan")就會放在db1中school文件夾下,class文件夾下的student_name中
3.配置controller和應用
public class CustomerController : Controller
{
IDistributedCache _distributedCache;
public CustomerController( IDistributedCache distributedCache)
{
_distributedCache = distributedCache;
}
public string Get()
{
//將數據放入redis中
_distributedCache.SetString(“name”, "zhangsan");
var value = _distributedCache.GetString("name");
return value ;
}
}
以上即是Redis的使用配置,如果想要吧session的數據直接存儲到Redis中需要添加下Session的包以及做一下配置,session就會自動存儲在redis中。
