在.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. 计数器

最新文章

  1. linux备份mysq脚本
  2. Android 网络通信API的选择和实现实例
  3. Android 短信的还原
  4. Ubuntu PostgreSQL安装和配置
  5. WebService学习总结(二)——WebService相关概念介绍
  6. asp.net mvc 4 编译错误 CS0012
  7. HTML转换成word文档
  8. Linux如何在虚拟机中挂载iso yum源
  9. 从 mian 函数开始一步一步分析 nginx 执行流程(二)
  10. 6.ListView
  11. C#(Net)软件开发常用工具汇总,提高你的开发效率
  12. (DP)Best Time to Buy and Sell Stock
  13. 把事务封装成类似Serializable用法的特性
  14. 【JS学习笔记】关于function函数
  15. QT中LineEdit、TextEdit 、PlainTextEdit 三个控件的区别
  16. 在Synology群晖上运行Frp客户端
  17. 金融量化分析【day111】:Matplotib-图标标注
  18. Java处理对象
  19. Spring核心之IOC
  20. MySQl 查询性能优化相关

热门文章

  1. [模板] 虚树 &amp;&amp; bzoj2286-[Sdoi2011]消耗战
  2. python之函数闭包、可迭代对象和迭代器
  3. GitHub最基本使用总结
  4. java 从指定行读文件,执行系统命令
  5. Linux系统初始化配置项(centos7)
  6. FWT快速沃尔什变换学习笔记
  7. &lt;Android基础&gt; (四) Fragment Part 2
  8. latex 一些使用
  9. 使用 gzexe 快速加密解密文件内容
  10. 第十一节:Bundles压缩合并js和css及原理分析