AspNetCore WebAPi中Redis的简单使用
参考(2条消息) .NET Core Redis的简单使用_sunshineGGB的博客-CSDN博客_.net core redis
一、首先电脑安装Redis服务:
官网:https://github.com/tporadowski/redis/releases
下载解压后在文件夹下cmd:(可以配置环境变量到全局)
启动服务:
.\redis-server.exe redis.windows.conf
Redis常用命令:
安装服务:redis-server --service-install 卸载服务:redis-server --service-uninstall 开启服务:redis-server --service-start 停止服务:redis-server --service-stop 服务端启动时重命名:redis-server --service-start --service-name Redis1 启动客户端:redis-cli 退出客户端:quit
二、AspNetCoreWebApi为例子:
1、安装包
2、配置:
添加IRedisServices
public interface IRedisServices { bool SetValue(string key, string value); string GetValue(string key); bool DeleteKey(string key); }
添加RedisServices
public class RedisServices : IRedisServices { public ConnectionMultiplexer redis { get; set; } public IDatabase db { get; set; } private IConfiguration _config; public RedisServices(IConfiguration configuration) { _config = configuration; redis = ConnectionMultiplexer.Connect(_config["RedisServer"]); db = redis.GetDatabase(); } /// <summary> /// 增加/修改 /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <returns></returns> public bool SetValue(string key, string value) { return db.StringSet(key, value); } /// <summary> /// 查询 /// </summary> /// <param name="key"></param> /// <returns></returns> public string GetValue(string key) { return db.StringGet(key); } /// <summary> /// 删除 /// </summary> /// <param name="key"></param> /// <returns></returns> public bool DeleteKey(string key) { return db.KeyDelete(key); } }
添加生命周期
services.AddTransient<IRedisServices, RedisService>();
3、使用:
[EnableCors("Policy")] [Route("api/[controller]/[action]")] [ApiController] public class RedisController : ControllerBase { private readonly IRedisServices _redisServices; public RedisController(IRedisServices redisServices) { _redisServices = redisServices; } [HttpGet] public IActionResult GetRedisValue([FromQuery] string key) { var value = _redisServices.GetValue(key); return Ok(value); } [HttpGet] public IActionResult SetRedisKeyValue([FromQuery] string key, [FromQuery] string value) { _redisServices.SetValue(key, value); return Ok(); } }
可视化Key values
安装Redis Assistant(免费)
官网:http://www.redisant.cn/
效果: