当前位置:网站首页>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
边栏推荐
- Use split to solve the "most common words" problem
- C# WPF UI框架MahApps切换主题
- 如果通过 C# 实现对象的深复制 ?
- MYSQL04_ Exercises corresponding to arithmetic, logic, bit, operator and operator
- Systemctl start Prometheus + grafana environment
- C#中切片语法糖的使用
- 使用两种方法来解决“最大回文数乘积”问题
- Thoughts on the 2022 national network security competition of the national secondary vocational group (only one idea for myself) - network security competition questions (9)
- [software testing] understand the basic knowledge of software testing
- Source generator actual combat
猜你喜欢

树莓派开发笔记(十二):入手研华ADVANTECH工控树莓派UNO-220套件(一):介绍和运行系统
![Introduction to ACM [TSP problem]](/img/9f/4e3592542d989b2fbb6d82f7f2fbd2.png)
Introduction to ACM [TSP problem]

tf. keras. layers. Conv? D function

Maui initial experience: Cool

Cherno_ Game engine series tutorial (5): 101~

Summary of software test interview questions

編碼電機PID調試(速度環|比特置環|跟隨)

ASP. Net 6 middleware series - execution sequence

Opencv combines multiple pictures into video

Ningde's position in the times is not guaranteed?
随机推荐
Using positive and negative traversal to solve the problem of "the shortest distance of characters"
tf. keras. layers. Timedistributed function
Opencv combines multiple pictures into video
svg标签中利用<polygon/>循环数组绘制多边形
C#中切片语法糖的使用
Recursion - outputs continuously increasing numbers
7-11 重排链表 (25 分)
编码电机PID调试(速度环|位置环|跟随)
Binary tree
Onenet connection process
搭建XAMPP时mysql端口被占用
Openfeign timeout setting
.NET点滴:说说Middleware构造中获取不到Scoped服务的问题
樹莓派開發筆記(十二):入手研華ADVANTECH工控樹莓派UNO-220套件(一):介紹和運行系統
TP5 multi conditional where query (using PHP variables)
Impact of AOT and single file release on program performance
ASP.NET 6 中间件系列 - 条件中间件
MYSQL_ From mastery to abandonment
Niuke white moon race 6 [solution]
Judge whether there is a leap year in the given year