一.准备
在.Net Core项目中使用StackExChange.Redis来使用Redis,这里通过Nuget去安装相关的包。安装完如下图。
二.配置
在appsettings.json中配置Redis的相关信息。一般需要配置连接地址、实例名、哪个DB、密码。
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } }, "AllowedHosts": "*", "Redis": { "Default": { "Connection": "127.0.0.1:6379", "InstanceName": "local", "DefaultDB": 0, "Password": "12345" } } }
三.使用
在Startup.cs中添加redis的依赖。
public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { //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").Value ?? "0"); //密码 string _password = section.GetSection("Password").Value; //注入容器 services.AddSingleton(new RedisHelper(_connectionString, _instanceName, _password, _defaultDB)); }
Redis使用类的定义。
public class RedisHelper : IDisposable { //连接字符串 private string _connectionString; //实例名称 private string _instanceName; //密码 private string _password; //默认数据库 private int _defaultDB; private ConcurrentDictionary<string, ConnectionMultiplexer> _connections; public RedisHelper(string connectionString, string instanceName, string password, int defaultDB = 0) { _connectionString = connectionString; _instanceName = instanceName; _password = password; _defaultDB = defaultDB; _connections = new ConcurrentDictionary<string, ConnectionMultiplexer>(); } /// <summary> /// 获取ConnectionMultiplexer /// </summary> /// <returns></returns> private ConnectionMultiplexer GetConnect() { return _connections.GetOrAdd(_instanceName, p => ConnectionMultiplexer.Connect(_connectionString + ",password=" + _password)); } /// <summary> /// 获取数据库 /// </summary> /// <param name="configName"></param> /// <param name="db">默认为0:优先代码的db配置,其次config中的配置</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(); } } } }
在接口中注入依赖去使用。
[Route("api/test")] [ApiController] public class TestController : ControllerBase { private readonly IDatabase _redis; public TestController(RedisHelper client) { //创建Redis连接对象 _redis = client.GetDatabase(); } //格式 string //cmd: getset key value [Route("set")] [HttpPost] public string Set(string key, string value) { string result; // 往Redis里面存入数据 if (_redis.StringSet(key, value)) { result = "成功"; } else { result = "失败"; } return result; } //格式 string //cmd: get key [Route("get")] [HttpGet] public string Get(string key) { // 从Redis里面取数据 string value = _redis.StringGet(key); return value; } //格式 hash //cmd: hset key field value [Route("hset")] [HttpPost] public string HSet(string key, string hashField, string value) { string result; // 往Redis里面存入数据 if (_redis.HashSet(key, hashField, value)) { result = "成功"; } else { result = "失败"; } return result; } //格式 hash //cmd: hget key field [Route("hget")] [HttpGet] public string HGet(string key, string hashField) { // 从Redis里面取数据 string value = _redis.HashGet(key, hashField); return value; } }
IDataBase接口定义了方法,基本包括了Redis操作的各个方法,可以参考Redis的命令行方法来查找对应的方法。
Redis命令可以参考这篇 https://www.cnblogs.com/shadoll/p/14388289.html
四.总结
1.在.Net Core安装Redis使用的StackExChange.Redis包,确保Redis服务处于正常启动状态,配置连接项即可。
2.熟悉Redis的命令行操作,就可以大致了解StackExChange.Redis的使用方法(它底层应该也是执行Redis的命令操作)。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:.Net Core使用Redis - Python技术站