asp.net core 运用 Redis 配置步骤

Redis能够用来存储session或直接存储键值对web

首先要有asp.net core的项目,能够是webapi 或者MVC项目,redis

还有有本地的Redis或者在远程服务器上,具体的安装就不讲述了 如下是具体配置过程:api

1.安装 "Microsoft.Extensions.Caching.Redis.Core": "1.0.3"(版本根据本身的好项目的需求自行选择,本次以1.0.3为例展现)服务器

2.配置startup.cssession

public void ConfigureServices(IServiceCollection services)
    {
          services.AddDistributedRedisCache(options =>
            {
                options.InstanceName = "school:class:student_";
                   options.Configuration="127.0.0.1:6379,password=1234,defaultdatabase=1";
            }); 
    }

 defaultdatabase 定义了数据保存的位置 1 就是默认载db1中asp.net

InstanceName 定义了添加的数据所在的文件路径以及前缀,“:”是层次的分隔符,好比“school:class:student_” 添加的数据("name":"zhangsan")就会放在db1中school文件夹下,class文件夹下的student_name中spa

3.配置controller和应用.net

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中。code

相关文章
相关标签/搜索