当前位置:网站首页>Yes Redis using distributed cache in NE6 webapi
Yes Redis using distributed cache in NE6 webapi
2022-04-23 03:07:00 【Rodinia lava】
First installation Redis
https://github.com/MicrosoftArchive/redis/releases
https://github.com/cinience/RedisStudio/releases
Redis Startup and shutdown
Once installed , We can start and shut down through services Redis 了 , We can view the task manager of the system , Check if... Is started redis-server, Here is redis-server Startup and shutdown commands :
$ redis-server.exe --service-start # start-up
$ redis-server.exe --service-stop # close
Use cli
confirm redis-server After starting , We can execute redis In the catalog redis-cli.exe file , So you can connect to Redis 了 . Of course , We can also use the command line CMD To link Redis.
It can be done directly Redis Accessed :
$ redis-cli.exe -h 127.0.0.1 -p 6379
127.0.0.1:6379> set firstKey "moyufed"
OK
127.0.0.1:6379> get firstKey
"moyufed"
127.0.0.1:6379>
Add password
stay Redis In the installation directory of , Yes redis.windows.conf ,redis.windows-service.conf Two documents , We use Notepad to open ( recommend Notepad++), Find the line that needs to set the password , Sure Ctrl + F lookup “requirepass” The line of ( Probably 386 Row position ), Set separately Redis password ( Get rid of the front “#”), Example :
requirepass moyufed
Use Redis
Restart after modification redis-server , Now connect Redis after Redis Access requires login , Example :
Administrator@WIN-1706081829 C:\Users\Administrator
$ redis-server.exe --service-stop
[42636] 25 Feb 18:42:53.622 # Redis service successfully stopped.
Administrator@WIN-1706081829 C:\Users\Administrator
$ redis-server.exe --service-start
[38828] 25 Feb 18:42:58.576 # Redis service successfully started.
Administrator@WIN-1706081829 C:\Users\Administrator
$ redis-cli.exe -h 127.0.0.1 -p 6379
127.0.0.1:6379> set firstKey "moyufed"
(error) NOAUTH Authentication required.
127.0.0.1:6379> auth moyufed
OK
127.0.0.1:6379> set firstKey "moyufed"
OK
127.0.0.1:6379> get firstKey
"moyufed"
127.0.0.1:6379>
Reference documents
Window To configure Redis Environment and simple use :https://www.cnblogs.com/wxjnew/p/9160855.html
Windows Next Redis Installation, configuration and use precautions :https://www.cnblogs.com/LMJBlogs/p/11550170.html
First configuration .NET6 Installation environment of
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Caching.StackExchangeRedis" Version="6.0.4" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="6.0.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Abstractions" Version="6.0.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="6.0.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="6.0.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="6.0.3">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="6.0.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Options" Version="6.0.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
<PackageReference Include="NModbus4.NetCore" Version="2.0.1" />
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="6.0.1" />
</ItemGroup>
</Project>
Configure the data warehouse :
public record Book
{
public int Id {
get; set; }
public string Name {
get; set; }
public double Price {
get; set; }
}
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
class BookConfig : IEntityTypeConfiguration<Book>
{
public void Configure(EntityTypeBuilder<Book> builder)
{
builder.ToTable("Books");
builder.HasKey(x => x.Id);
}
}
using Microsoft.EntityFrameworkCore;
public class MyDbContext : DbContext
{
private ConfigurationBuilder cfgBuilder = new ConfigurationBuilder();
private string path = Directory.GetCurrentDirectory();
public DbSet<Book> Books {
get; set; }
public MyDbContext()
{
//configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("Ipcfg.json").Build();
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.ApplyConfigurationsFromAssembly(this.GetType().Assembly);
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
cfgBuilder.AddJsonFile("VariableNode.json", optional: true, reloadOnChange: true);
IConfigurationRoot configRoot = cfgBuilder.Build();
string conn = configRoot.GetSection("ConnectionStrings:SqliteConnectionString").Value;
string connString = "Data Source=" + path + conn;
optionsBuilder.UseSqlite(connString);
}
}
{
"ConnectionStrings": {
"SqliteConnectionString": "\\bin\\Debug\\net6.0\\Database\\DbSqlite.db",
"MySQLConnectionString": "server=192.168.85.102; database=OneToMany; uid=root; pwd=123456;"
},
"ModbusNode": {
"Id": 1,
"NodeClassId": 1,
"Name": "ModbusTCPClient",
"Description": "1#ZG Upper computer test ",
"ModbusType": "2000",
"ConnectTimeOut": "2000",
"CreateTime": "0",
"ReConnectTime": "5000",
"IsActive": "True",
"MaxErrorTimes": "1",
"KeyWay": "VarName",
"UseAlarmCheck": "True",
"ServerURL": "127.0.0.1",
"Port": "502",
"DataFormat": "ABCD",
"VarNum": "6",
"Type": "ModbusTCP",
"SlaveID": "1",
"Length": "10",
"Start": "0",
"Variable": [
{
"Id": 1,
"Number": "1",
"Name": "Float1",
"Description": "40001-40002",
"Type": "ModbusTCP",
"VarAddress": 0,
"Scale": "1",
"Offset": "0",
"Start": "0",
"AccessProperty": " Reading and writing ",
"AlarmEnable": "True",
"ArchiveEnable": "True",
"SetLimitEnable": "True",
"AlarmType": "True",
"DiscreteAlarmType": "False",
"DiscreteAlarmPriority": "0",
"DiscreteAlarmNote": "null",
"LoLoAlarmEnable": "True",
"LoLoAlarmValue": "0",
"LoLoAlarmPriority": "0",
"LoLoAlarmNote": "40001-40002 Low low alarm ",
"LowAlarmEnable": "True",
"LowAlarmValue": "20",
"LowAlarmPriority": "0",
"LowAlarmNote": "40001-40002 Low alarm ",
"HighAlarmEnable": "True",
"HighAlarmValue": "80",
"HighAlarmPriority": "0",
"HighAlarmNote": "40001-40002 High alarm ",
"HiHiAlarmEnable": "True",
"HiHiAlarmValue": "100",
"HiHiAlarmPriority": "0",
"HiHiAlarmNote": "40001-40002 High high alarm ",
"ArchivePeriod": "80",
"SetLimitMax": "100",
"SetLimitMin": "0",
"VarType": "Float",
"StoreType": "HoldingRegister4x",
"InsertTime": "0",
"Value": "0",
"ModbusGroupId": 1
},
{
"Id": 2,
"Number": "2",
"Name": "Float2",
"Description": "40003-40004",
"Type": "ModbusTCP",
"VarAddress": 2,
"Scale": "1",
"Offset": "0",
"Start": "0",
"AccessProperty": " Reading and writing ",
"AlarmEnable": "True",
"ArchiveEnable": "True",
"SetLimitEnable": "True",
"AlarmType": "True",
"DiscreteAlarmType": "False",
"DiscreteAlarmPriority": "0",
"DiscreteAlarmNote": "null",
"LoLoAlarmEnable": "True",
"LoLoAlarmValue": "0",
"LoLoAlarmPriority": "0",
"LoLoAlarmNote": "40003-40004 Low low alarm ",
"LowAlarmEnable": "True",
"LowAlarmValue": "20",
"LowAlarmPriority": "0",
"LowAlarmNote": "40003-40004 Low alarm ",
"HighAlarmEnable": "True",
"HighAlarmValue": "80",
"HighAlarmPriority": "0",
"HighAlarmNote": "40003-40004 High alarm ",
"HiHiAlarmEnable": "True",
"HiHiAlarmValue": "100",
"HiHiAlarmPriority": "0",
"HiHiAlarmNote": "40003-40004 High high alarm ",
"ArchivePeriod": "80",
"SetLimitMax": "100",
"SetLimitMin": "0",
"VarType": "Float",
"StoreType": "HoldingRegister4x",
"InsertTime": "0",
"Value": "0",
"ModbusGroupId": 1
},
{
"Id": 3,
"Number": "3",
"Name": "Float3",
"Description": "40005-40006",
"Type": "ModbusTCP",
"VarAddress": 4,
"Scale": "1",
"Offset": "0",
"Start": "0",
"AccessProperty": " Reading and writing ",
"AlarmEnable": "True",
"ArchiveEnable": "True",
"SetLimitEnable": "True",
"AlarmType": "True",
"DiscreteAlarmType": "False",
"DiscreteAlarmPriority": "0",
"DiscreteAlarmNote": "null",
"LoLoAlarmEnable": "True",
"LoLoAlarmValue": "0",
"LoLoAlarmPriority": "0",
"LoLoAlarmNote": "40005-40006 Low low alarm ",
"LowAlarmEnable": "True",
"LowAlarmValue": "20",
"LowAlarmPriority": "0",
"LowAlarmNote": "40005-40006 Low alarm ",
"HighAlarmEnable": "True",
"HighAlarmValue": "80",
"HighAlarmPriority": "0",
"HighAlarmNote": "40005-40006 High alarm ",
"HiHiAlarmEnable": "True",
"HiHiAlarmValue": "100",
"HiHiAlarmPriority": "0",
"HiHiAlarmNote": "40005-40006 High high alarm ",
"ArchivePeriod": "80",
"SetLimitMax": "100",
"SetLimitMin": "0",
"VarType": "Float",
"StoreType": "HoldingRegister4x",
"InsertTime": "0",
"Value": "0",
"ModbusGroupId": 1
},
{
"Id": 4,
"Number": "4",
"Name": "Float4",
"Description": "40007-40008",
"Type": "ModbusTCP",
"VarAddress": 6,
"Scale": "1",
"Offset": "0",
"Start": "0",
"AccessProperty": " Reading and writing ",
"AlarmEnable": "True",
"ArchiveEnable": "True",
"SetLimitEnable": "True",
"AlarmType": "True",
"DiscreteAlarmType": "False",
"DiscreteAlarmPriority": "0",
"DiscreteAlarmNote": "null",
"LoLoAlarmEnable": "True",
"LoLoAlarmValue": "0",
"LoLoAlarmPriority": "0",
"LoLoAlarmNote": "40003-40004 Low low alarm ",
"LowAlarmEnable": "True",
"LowAlarmValue": "20",
"LowAlarmPriority": "0",
"LowAlarmNote": "40003-40004 Low alarm ",
"HighAlarmEnable": "True",
"HighAlarmValue": "80",
"HighAlarmPriority": "0",
"HighAlarmNote": "40003-40004 High alarm ",
"HiHiAlarmEnable": "True",
"HiHiAlarmValue": "100",
"HiHiAlarmPriority": "0",
"HiHiAlarmNote": "40003-40004 High high alarm ",
"ArchivePeriod": "80",
"SetLimitMax": "100",
"SetLimitMin": "0",
"VarType": "Float",
"StoreType": "HoldingRegister4x",
"InsertTime": "0",
"Value": "0",
"ModbusGroupId": 1
},
{
"Id": 5,
"Number": "5",
"Name": "Ushort1",
"Description": "40009",
"Type": "ModbusTCP",
"VarAddress": 8,
"Scale": "1",
"Offset": "0",
"Start": "0",
"AccessProperty": " Reading and writing ",
"AlarmEnable": "True",
"ArchiveEnable": "True",
"SetLimitEnable": "True",
"AlarmType": "True",
"DiscreteAlarmType": "False",
"DiscreteAlarmPriority": "0",
"DiscreteAlarmNote": "null",
"LoLoAlarmEnable": "True",
"LoLoAlarmValue": "0",
"LoLoAlarmPriority": "0",
"LoLoAlarmNote": "40009 Low low alarm ",
"LowAlarmEnable": "True",
"LowAlarmValue": "20",
"LowAlarmPriority": "0",
"LowAlarmNote": "40009 Low alarm ",
"HighAlarmEnable": "True",
"HighAlarmValue": "80",
"HighAlarmPriority": "0",
"HighAlarmNote": "40009 High alarm ",
"HiHiAlarmEnable": "True",
"HiHiAlarmValue": "100",
"HiHiAlarmPriority": "0",
"HiHiAlarmNote": "40009 High high alarm ",
"ArchivePeriod": "80",
"SetLimitMax": "100",
"SetLimitMin": "0",
"VarType": "UShort",
"StoreType": "HoldingRegister4x",
"InsertTime": "0",
"Value": "0",
"ModbusGroupId": 1
},
{
"Id": 6,
"Number": "6",
"Name": "Ushort2",
"Description": "40010",
"Type": "ModbusTCP",
"VarAddress": 9,
"Scale": "1",
"Offset": "0",
"Start": "0",
"AccessProperty": " Reading and writing ",
"AlarmEnable": "True",
"ArchiveEnable": "True",
"SetLimitEnable": "True",
"AlarmType": "True",
"DiscreteAlarmType": "False",
"DiscreteAlarmPriority": "0",
"DiscreteAlarmNote": "null",
"LoLoAlarmEnable": "True",
"LoLoAlarmValue": "0",
"LoLoAlarmPriority": "0",
"LoLoAlarmNote": "40009 Low low alarm ",
"LowAlarmEnable": "True",
"LowAlarmValue": "20",
"LowAlarmPriority": "0",
"LowAlarmNote": "40009 Low alarm ",
"HighAlarmEnable": "True",
"HighAlarmValue": "80",
"HighAlarmPriority": "0",
"HighAlarmNote": "40009 High alarm ",
"HiHiAlarmEnable": "True",
"HiHiAlarmValue": "100",
"HiHiAlarmPriority": "0",
"HiHiAlarmNote": "40009 High high alarm ",
"ArchivePeriod": "80",
"SetLimitMax": "100",
"SetLimitMin": "0",
"VarType": "UShort",
"StoreType": "HoldingRegister4x",
"InsertTime": "0",
"Value": "0",
"ModbusGroupId": 1
}
]
}
}
namespace RedisDemonWebApi
{
public interface IRepository
{
Book? GetBooksByIdAsync(int a);
}
}
namespace RedisDemonWebApi
{
public class Repository : IRepository
{
private MyDbContext db;
public Repository(MyDbContext db)
{
this.db = db;
}
public Book? GetBooksByIdAsync(int a)
{
Book? book = db.Books.Where(x => x.Id == a).SingleOrDefault();
if (book==null)
{
return null;
}
else
{
return book;
}
//return db.Books.Single(x => x.Id == a);
}
}
}
Dependency injection :
global using RedisDemonWebApi;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddMemoryCache();// Memory cache
builder.Services.AddScoped<IMemoryCacheHelper, MemoryCacheHelper>();
builder.Services.AddDbContext<MyDbContext>();
builder.Services.AddScoped<IRepository, Repository>();
builder.Services.AddStackExchangeRedisCache(opt =>
{
opt.Configuration = "localhost";
opt.InstanceName = "cache1_";
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
controller :
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Caching.Memory;
using System.Text.Json;
namespace RedisDemonWebApi.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class TestController : ControllerBase
{
private readonly IDistributedCache distCache;
private readonly IDistributedCacheHelper helper;
private readonly ILogger <TestController> logger;
private readonly IMemoryCache memCache;
private readonly IRepository repository;
public TestController(IRepository repository, IMemoryCache memCache, ILogger<TestController> logger, IDistributedCache distCache)
{
//this.distCache = distCache;
//this.helper = helper;
this.repository = repository;
this.memCache = memCache;
this.logger = logger;
this.distCache = distCache;
}
//[HttpGet]
//public string Now()
//{
// string s = distCache.GetString("Now");
// if (s == null)
// {
// s = DateTime.Now.ToString();
// var opt = new DistributedCacheEntryOptions();
// opt.AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(30);
// distCache.SetString("Now", s, opt);
// }
// return s;
//}
[HttpGet]
//public ActionResult<Book?> GetBookById(int Id)
//{
// Book? book = repository.GetBooksByIdAsync(Id);
// return Ok(book);
//}
// Memory cache
public async Task<ActionResult<Book?>> GetBookById(int Id)
{
logger.LogInformation($" Start execution GetBookById,Id={
Id}");
// First look for the memory cache , No re-entry repository lookup
Book? b = await memCache.GetOrCreateAsync("Book" + Id, async (e) =>
{
logger.LogInformation($" Not found in cache , Go to the database ,Id={
Id}");
return repository.GetBooksByIdAsync(Id);
});
logger.LogInformation($"GetOrCreateAsync result {
b}");
if (b == null)
{
return NotFound(" Can't find ");
}
else
{
return Ok(b);
}
}
// Distributed cache
[HttpGet]
public async Task<ActionResult<Book?>> GetBookFromRedisById(int Id)
{
Book? book=null;
logger.LogInformation($" Start execution GetBookById,Id={
Id}");
// First go to the distributed cache to find
string? s = await distCache.GetStringAsync("Book" + Id);
// If not , Go to the database and find , Then it is stored in the distributed cache
if (s==null)
{
logger.LogInformation($" Not found in cache , Go to the database and find ,Id={
Id}");
book = repository.GetBooksByIdAsync(Id);
// Set up Redis Expiration time in opt
var opt = new DistributedCacheEntryOptions();
opt.AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(30);
//json Serialize into a string and store it in the cache
await distCache.SetStringAsync("Book" + Id, JsonSerializer.Serialize(book), opt);
logger.LogInformation($" Find... In the database ,Id={
Id}, Serialize it into a string and store it in Redis");
}
// If found in cache , You need to set the string in the cache s Deserialize to book
else
{
book = JsonSerializer.Deserialize<Book?>(s);
logger.LogInformation($" Directly in Redis Found in the ,Id={
Id}");
}
// If you don't find it, it doesn't exist
if (book==null)
{
logger.LogInformation($" Database and Redis None of them exist Id={
Id} Books ");
return NotFound(" non-existent ");
}
else
{
return book;
}
}
}
}
Use Swagger test :

journal :
info: Microsoft.Hosting.Lifetime[14]
Now listening on: https://localhost:7063
info: Microsoft.Hosting.Lifetime[14]
Now listening on: http://localhost:5063
info: Microsoft.Hosting.Lifetime[0]
Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
Hosting environment: Development
info: Microsoft.Hosting.Lifetime[0]
Content root path: D:\cSharpe\code\RedisDemon1\RedisDemonWebApi\
info: RedisDemonWebApi.Controllers.TestController[0]
Start execution GetBookById,Id=2
info: RedisDemonWebApi.Controllers.TestController[0]
Not found in cache , Go to the database and find ,Id=2
info: RedisDemonWebApi.Controllers.TestController[0]
Find... In the database ,Id=2, Serialize it into a string and store it in Redis
info: RedisDemonWebApi.Controllers.TestController[0]
Start execution GetBookById,Id=2
info: RedisDemonWebApi.Controllers.TestController[0]
Directly in Redis Found in the ,Id=2
Redis in :

If the inquiry Id The corresponding content does not exist , be Redis Will also put null The value is Redis, This avoids the problem of cache penetration

版权声明
本文为[Rodinia lava]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230306056974.html
边栏推荐
- LNMP MySQL allows remote access
- Cherno_ Game engine series tutorial (5): 101~
- C read / write binary file
- Source code interpretation of Flink index parameters (read quantity, sent quantity, sent bytes, received bytes, etc.)
- In redis cluster, the master node fails, and the IP changes after the master-slave switch. The client does not need to deal with it
- 腾讯视频VIP会员,周卡特价9元!腾讯官方直充,会员立即生效!
- Numpy append function
- Xamarin效果第二十一篇之GIS中可扩展浮动操作按钮
- Opencv combines multiple pictures into video
- Openfeign details show
猜你喜欢

LNMP MySQL allows remote access

Blazor University (11)组件 — 替换子组件的属性

微软是如何解决 PC 端程序多开问题的——内部实现

由于3²+4²=5²,所以称‘3,4,5‘为勾股数,求n(包括n)以内所有勾股数数组。

svg标签中利用<polygon/>循环数组绘制多边形
![FileNotFoundError: [Errno 2] No such file or directory](/img/ea/0c3f2768d14c1f4bb42bd1309ab996.png)
FileNotFoundError: [Errno 2] No such file or directory

Deep q-network (dqn)

Distributed system services

The whole network is the most complete. How to do interface automation test? Proficient in interface automation test details

Xamarin效果第二十二篇之录音效果
随机推荐
求二叉树的叶子结点个数
C#中元组对象Tuple的使用
c#语法糖模式匹配【switch 表达式】
Redis Cluster集群,主节点故障,主从切换后ip变化,客户端需要处理不
.NET7之MiniAPI(特别篇):.NET7 Preview3
由于3²+4²=5²,所以称‘3,4,5‘为勾股数,求n(包括n)以内所有勾股数数组。
Introduction to ACM [inclusion exclusion theorem]
ASP.NET 6 中间件系列 - 自定义中间件类
如果通过 C# 实现对象的深复制 ?
Tencent video VIP member, weekly card special price of 9 yuan! Tencent official direct charging, members take effect immediately!
.Net Core 限流控制-AspNetCoreRateLimit
Er and eer models
MYSQL_ From mastery to abandonment
tf. keras. layers. MaxPooling? D function
Realize QQ login with PHP
使用split来解决“最常见的单词”问题
tf. keras. layers. Conv? D function
Thoughts on the 2022 national network security competition of the national secondary vocational group (only one idea for myself) - network security competition questions (10)
樹莓派開發筆記(十二):入手研華ADVANTECH工控樹莓派UNO-220套件(一):介紹和運行系統
Xamarin效果第二十一篇之GIS中可扩展浮动操作按钮