Redis实战 - 1.String和计数器

在.NET Core 项目中操练String
使用 StackExchange.Redis 访问 Redis
static void Main(string[] args)
{
using (ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("localhost:6379"))
{
IDatabase db = redis.GetDatabase();
db.StringSet("name", "Michal Jackson");
string name = db.StringGet("name");
Console.WriteLine(name); //结果:Michal Jackson
db.StringSet("age", "11");
//incr 自增
db.StringIncrement("age");
RedisValue age = db.StringGet("age");
Console.WriteLine(age);//结果:12
//incrby 指定增量
age = db.StringIncrement("age", 5);
Console.WriteLine(age);//结果:17
//decr 自减
age = db.StringDecrement("age");
Console.WriteLine(age);//结果:16
//decrby 指定减量
age = db.StringDecrement("age", 5);
Console.WriteLine(age);//结果:11
//mset 设置多个值
db.StringSet(new KeyValuePair<RedisKey, RedisValue>[]
{
new KeyValuePair<RedisKey, RedisValue>("aa", "aa"),
new KeyValuePair<RedisKey, RedisValue>("bb", "bb"),
new KeyValuePair<RedisKey, RedisValue>("cc", "5"),
});
//mget 取多个值
var values = db.StringGet(new RedisKey[] { "aa", "bb", "cc" });
foreach (RedisValue redisValue in values)
{
Console.Write(redisValue + ",");
}
//结果:aa,bb,5
//exists 是否存在
db.StringSet("name1", "Dave1");
bool existsResult = db.KeyExists("name1");
Console.WriteLine(existsResult); //结果:true
//del 删除
bool delResult = db.KeyDelete("name1");
Console.WriteLine(delResult); //结果:true
existsResult = db.KeyExists("name1");
Console.WriteLine(existsResult); //结果:false
//type 判断类型
db.StringSet("name2", "Dave2");
var typeOfValue = db.KeyType("name2");
Console.WriteLine(typeOfValue); //String
//expire 过期时间
db.StringSet("name3", "Dave3");
db.KeyExpire("name3", TimeSpan.FromSeconds(5));
RedisValue value = db.StringGet("name3");
Console.WriteLine(value); //Dave3
Console.WriteLine("此处等待6秒...");
Thread.Sleep(6 * 1000);
value = db.StringGet("name3"); //啥也没有..
Console.WriteLine(value);
//ex 设置key直接设置有效期
db.StringSet("name4","Dave4", TimeSpan.FromSeconds(5));
RedisValue value4 = db.StringGet("name4");
Console.WriteLine(value4); //Dave4
Console.WriteLine("此处等待6秒...");
Thread.Sleep(6 * 1000);
value4 = db.StringGet("name4"); //啥也没有..
Console.WriteLine(value4);
//ttl 查看过期时间
db.StringSet("name6","Dave6", TimeSpan.FromSeconds(5));
for (int i = 1; i < 7; i++)
{
Thread.Sleep( 1000);
RedisValue valueTTL = db.StringGet("name6");
var ttl = db.KeyTimeToLive("name6");
if (ttl==null)
{
Console.WriteLine($"{i}秒过后:Dave6已过期");
}
else
{
Console.WriteLine($"{i}秒过后:{valueTTL}还能存活{ttl}秒");
}
}
// 1秒过后:Dave6还能存活00:00:03.9970000秒
// 2秒过后:Dave6还能存活00:00:02.9040000秒
// 3秒过后:Daue6还能存活00:00:01.9040000秒
// 4秒过后:Dave6还能存活00:00:00.9030000秒
// 5秒过后:Dave6已过期
// 6秒过后:Daue6已过期
}
Console.ReadKey();
}
1.string值写到前台,取RedisValue
先 Startup.cs 注入 IConnectionMultiplexer
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddSingleton<IConnectionMultiplexer>(ConnectionMultiplexer.Connect("localhost:6379"));
在 HomeController.cs
public class HomeController : Controller
{
private readonly IConnectionMultiplexer _redis;
private readonly IDatabase _db;
public HomeController(IConnectionMultiplexer redis)
{
_redis = redis;
_db = _redis.GetDatabase();
}
public IActionResult Index()
{
_db.StringSet("fullname", "Michael Jackson");
var name = _db.StringGet("fullname");
return View("Index", name);
}
}
视图 Index
@model StackExchange.Redis.RedisValue
<div class="text-center">
<h1 class="display-4"> Welcome:@Model </h1>
<p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
</div>

2.计数器
2.1 视图组件 ViewComponent
创建 CounterViewComponent 类
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using StackExchange.Redis;
namespace RedisToEsay.ViewComponents
{
public class CounterViewComponent : ViewComponent
{
private readonly IDatabase _db;
public CounterViewComponent(IConnectionMultiplexer redis)
{
_db = redis.GetDatabase();
}
public async Task<IViewComponentResult> InvokeAsync()
{
string controller = RouteData.Values["controller"].ToString();
string action = RouteData.Values["action"].ToString();
if (!string.IsNullOrWhiteSpace(controller) && !string.IsNullOrWhiteSpace(action))
{
var pageId = $"{controller}-{action}";
await _db.StringIncrementAsync(pageId);
var count = _db.StringGet(pageId);
return View("Default", pageId + ":" + count);
}
throw new Exception("can't get pageId");
}
}
}
创建 Default 视图
@model string
<h4>@Model</h4>
然后在Shared_Layout.cshtml 调用
<div>
@await Component.InvokeAsync("Counter")
</div>
报错:Defualt 创建的位置不对
An unhandled exception occurred while processing the request.
InvalidOperationException: The view 'Components/Counter/Default' was not found. The following locations were searched:
/Views/Home/Components/Counter/Default.cshtml
/Views/Shared/Components/Counter/Default.cshtml
/Pages/Shared/Components/Counter/Default.cshtml
所以创建的位置在
/Views/Shared/Components/Counter/Default.cshtml


参考:
草根专栏,Redis in .NET Core 入门:(2) String
杨旭(Video),Redis in ASP.NET Core 1. 计数器
Redis实战 - 1.String和计数器的更多相关文章
- (转)国内外三个不同领域巨头分享的Redis实战经验及使用场景
随着应用对高性能需求的增加,NoSQL逐渐在各大名企的系统架构中生根发芽.这里我们将为大家分享社交巨头新浪微博.传媒巨头Viacom及图片分享领域佼佼者Pinterest带来的Redis实践,首先我们 ...
- C# Redis实战
转自 :http://blog.csdn.net/qiujialongjjj/article/details/16945569 一.初步准备 Redis 是一个开源的使用ANSI C 语言编写.支持 ...
- Redis实战之Redis + Jedis
用Memcached,对于缓存对象大小有要求,单个对象不得大于1MB,且不支持复杂的数据类型,譬如SET 等.基于这些限制,有必要考虑Redis! 相关链接: Redis实战 Redis实战之Redi ...
- Redis实战之征服 Redis + Jedis + Spring (一)
Redis + Jedis + Spring (一)—— 配置&常规操作(GET SET DEL)接着需要快速的调研下基于Spring框架下的Redis操作. 相关链接: Redis实战 Re ...
- Redis实战之征服 Redis + Jedis + Spring (二)
不得不说,用哈希操作来存对象,有点自讨苦吃! 不过,既然吃了苦,也做个记录,也许以后API升级后,能好用些呢?! 或许,是我的理解不对,没有真正的理解哈希表. 相关链接: Redis实战 Redis实 ...
- Redis实战之征服 Redis + Jedis + Spring (三)
一开始以为Spring下操作哈希表,列表,真就是那么土.恍惚间发现“stringRedisTemplate.opsForList()”的强大,抓紧时间恶补下. 通过spring-data-redis完 ...
- Redis实战之Redis + Jedis[转]
http://blog.csdn.net/it_man/article/details/9730605 2013-08-03 11:01 1786人阅读 评论(0) 收藏 举报 目录(?)[-] ...
- C# Redis实战(七)
七.修改数据 在上一篇 C# Redis实战(六)中介绍了如何查询Redis中数据,本篇将介绍如何修改Redis中相关数据.大家都知道Redis是key-value型存储系统,所以应该可以修改key, ...
- C# Redis实战(六)
六.查询数据 在C# Redis实战(五)中介绍了如何删除Redis中数据,本篇将继续介绍Redis中查询的写法. 1.使用Linq匹配关键字查询 using (var redisClient = R ...
随机推荐
- JS自动微信消息轰炸
打开网页版本微信,按f12,以console台 输入下边这段代码 setInterval(function(){$('.edit_area').html('需要发送的文字');$(".edi ...
- Python——电子邮件、Internet协议相关模块
一.电子邮件相关模块 email:用于处理电子邮件 smtpd:SMTP服务器 base64:Base-16.32.64数据编码 mhlib:处理MH文件格式解析的类 mailcap:mailcap文 ...
- Python pip Unable--
It is possible that pip does not get installed by default. One potential fix is: python -m ensurepip ...
- jap篇 之 JSTL标签库
JSTL标签库: JSTL: JSP Standard Tag Library 作用:和[EL配合]使用,可以让用户[尽可能少的使用java源码]. 1,导入jar包 导入(复制粘贴到项目中的lib目 ...
- oneinstack 安装 https-certbot
免费https? 官方安装教程:https://certbot.eff.org/#centos6-nginx (以下是说明安装时遇到的): 下载并修改文件权限 wget https://dl.ef ...
- mysql 设置允许重试,批量更新
jdbc:mysql://ip:port/base?allowMultiQueries=true&autoReconnect=true 在mybatis中批量更新 需要在mysql的url上设 ...
- 【洛谷P2822 组合数问题】
题目连接 #include<iostream> #include<cstring> #include<cstdio> #include<cctype> ...
- GoLang-Beego使用
1.beego 注意事项 beego的默认架构是mvc python的django默认是mtv package main import ( "github.com/astaxie/beego ...
- 系统磁盘优化——"/var/spool/postfix/maildrop"
文件清理 最近某服务器磁盘空间告警,在排查过程中发现"/var/spool/postfix/maildrop"目录下堆积了很多小文件,起初想直接删除,但是使用rm删除是提示“参数列 ...
- 剑指Offer_编程题_20
题目描述 从上往下打印出二叉树的每个节点,同层节点从左至右打印. /* struct TreeNode { int val; struct TreeNode *left; struct TreeN ...