使用redis
------------恢复内容开始------------
1显示要安装redis(Redis Desktop Manager可视化工具,可装可不装)
这个安装教程很多,这里就不细讲了,需要注意的是一些路径,安装在哪个盘
输入cmd提示不是内部命令,就要转到相应的redis目录下执行 (输入下面两行命名就可以往redis中设置值了,get key 和set key values)
如果装有可视化工具的话,效果是这样的默认连接是一样的
在appsetting设置
"Redis": { "Default": { "Connection": "127.0.0.1:6379", "InstanceName": "local", "DefaultDB": 0 } },
在startup中
// redis缓存 var section = Configuration.GetSection("Redis:Default"); //连接字符串 string _connectionString = section.GetSection("Connection").Value; //实例名称 string _instanceName = section.GetSection("InstanceName").Value; //默认数据库 int _defaultDB = int.Parse(section.GetSection("DefaultDB")); services.AddSingleton(new RedisHelper(_connectionString, _instanceName, _defaultDB));
建一个帮助类,与redis进行交互
public class RedisHelper : IDisposable (//引用空间注意是StackExchange.Redis) { //连接字符串 private string _connectionString; //实例名称 private string _instanceName; //默认数据库 private int _defaultDB; private ConcurrentDictionary<string, ConnectionMultiplexer> _connections; public RedisHelper(string connectionString, string instanceName, int defaultDB ) { _connectionString = connectionString; _instanceName = instanceName; _defaultDB = defaultDB; _connections = new ConcurrentDictionary<string, ConnectionMultiplexer>(); } /// <summary> /// 获取ConnectionMultiplexer /// </summary> /// <returns></returns> private ConnectionMultiplexer GetConnect() { return _connections.GetOrAdd(_instanceName, p => ConnectionMultiplexer.Connect(_connectionString)); } /// <summary> /// 获取数据库 /// </summary> /// <param name="configName"></param> /// <param name="db">/param> /// <returns></returns> public IDatabase GetDatabase() { return GetConnect().GetDatabase(_defaultDB); } public IServer GetServer(string configName = null, int endPointsIndex = 0) { var confOption = ConfigurationOptions.Parse(_connectionString); return GetConnect().GetServer(confOption.EndPoints[endPointsIndex]); } public ISubscriber GetSubscriber(string configName = null) { return GetConnect().GetSubscriber(); } public void Dispose() { if (_connections != null && _connections.Count > 0) { foreach (var item in _connections.Values) { item.Close(); } } } }
控制器使用
public class DemoController : Controller { private readonly IDatabase _redis; public DemoController(EFCoreDbContext dbContext, IMapper mapper, RedisHelper client) { _redis = client.GetDatabase(); } [HttpGet] public string Redis() { // 往Redis里面存入数据(将object转json也可以存) _redis.StringSet("1", "11"); // 从Redis里面取数据 string name = _redis.StringGet("1"); //从窗口设置的值 string a = _redis.StringGet("a"); return name; } }
nuget包是这个
然后就可以在调试,运行成功。