- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我编写了缓存更新功能。
这是我的 Redis 缓存实现:
public class RedisCache : ICache
{
private readonly IDatabase _cache;
public RedisCache(string connectionString)
{
var connection = ConnectionMultiplexer.Connect(connectionString);
_cache = connection.GetDatabase();
}
public async Task<T> GetAsync<T>(string key)
{
var value = await _cache.StringGetAsync(key);
if (value.HasValue)
{
return JsonConvert.DeserializeObject<T>(value);
}
return default(T);
}
public async Task SetAsync<T>(string key, T value, TimeSpan ttl)
{
var serializedValue = JsonConvert.SerializeObject(value);
await _cache.StringSetAsync(key, serializedValue, ttl);
}
public T Get<T>(string key)
{
var value = _cache.StringGet(key);
if (value.HasValue)
{
return JsonConvert.DeserializeObject<T>(value);
}
return default(T);
}
public void Set<T>(string key, T value, TimeSpan ttl)
{
var serializedValue = JsonConvert.SerializeObject(value);
_cache.StringSet(key, serializedValue, ttl);
}
public async Task RemoveAsync(string key)
{
await _cache.KeyDeleteAsync(key);
}
}
以及BackgroundService
中的用法:
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
using var scope = _serviceProvider.CreateScope();
_cache = scope.ServiceProvider.GetService<ICache>();
_queue = scope.ServiceProvider.GetService<RefresBackgroundQueue>();
await foreach (string item in _queue.DequeueAllAsync(stoppingToken))
{
try
{
// some logic
await _cache.GetAsync<Model>(key)
// some logic
await _cache.SetAsync(randomKey, result, new TimeSpan(100, 0, 0, 0));
}
catch (Exception ex)
{
_logger.LogError($"Exception while updating cache: {ex.Message}, {ex.StackTrace}");
}
}
}
从上面的代码中我得到了无法捕获的异常:
System.InvalidOperationException: Reading is not allowed after reader was completed.at System.IO.Pipelines.ThrowHelper.ThrowInvalidOperationException_NoReadingAllowed()at System.IO.Pipelines.Pipe.AdvanceReader(SequencePosition& consumed, SequencePosition& examined)at System.IO.Pipelines.Pipe.DefaultPipeReader.AdvanceTo(SequencePosition consumed, SequencePosition examined)at StackExchange.Redis.PhysicalConnection.ReadFromPipe() in /_/src/StackExchange.Redis/PhysicalConnection.cs:line 1729
遇到这种情况我该怎么办?
最佳答案
我在 BackgroundService.cs 中的 ExecuteAsync 中做了一些更改,
代码运行良好
ExecuteAsync 中的更改
完整代码
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;
public class MyBackgroundService : BackgroundService
{
private readonly IServiceProvider _serviceProvider;
private readonly ILogger<MyBackgroundService> _logger;
public MyBackgroundService(IServiceProvider serviceProvider, ILogger<MyBackgroundService> logger)
{
_serviceProvider = serviceProvider;
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
_logger.LogInformation("MyBackgroundService is starting.");
while (!stoppingToken.IsCancellationRequested)
{
// Your background service logic here
await Task.Delay(1000, stoppingToken); // Simulate some work
}
_logger.LogInformation("MyBackgroundService is stopping.");
using var scope = _serviceProvider.CreateScope();
var cache = scope.ServiceProvider.GetRequiredService<ICache>();
var queue = scope.ServiceProvider.GetRequiredService<RefreshBackgroundQueue>();
await foreach (string item in queue.DequeueAllAsync(stoppingToken))
{
try
{
// Your logic here
var key = item;
// Retrieve data from cache
var model = await cache.GetAsync<Model>(key);
// Perform some processing
var processedResult = ProcessModel(model);
// Store result in cache
var randomKey = Guid.NewGuid().ToString();
await cache.SetAsync(randomKey, processedResult, TimeSpan.FromDays(1)); // Adjust the TTL as needed
}
catch (Exception ex)
{
_logger.LogError($"Exception while updating cache: {ex.Message}, {ex.StackTrace}");
}
}
}
在代码中我使用了以下条件
while (!stoppingToken.IsCancellationRequested)
这是后台服务的主循环。只要取消 token (stoppingToken
) 尚未收到取消信号,它就会继续执行。取消 token 通常用于在应用程序关闭时正常停止后台操作。
await Task.Delay(1000,stoppingToken);
在循环内部,这行代码在循环迭代之间引入了 1000 毫秒(1 秒)的延迟。 await
关键字表示此操作是异步的,并允许其他任务在发生延迟时并发执行。
关于c# - Azure Redis 缓存 : Reading is not allowed after reader was completed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76904261/
class ReadLock { private: std::mutex readWriteMutex; std::mutex conditionmtx; std::condi
我在 utf-8 编码文件中有多个 messages.properties 文件(messages_en_US.properties、messages_fr.properties,...)。在这些属性
我正在尝试从 google reader api 中检索单个选定项目。是否可以通过 API 调用通过 ID 获取项目,或者我是否必须访问该项目提要并从那里获取它? 最佳答案 您可以使用 POST 到
好的,所以我有一个应用程序可以与 GR 的“api”紧密结合。 一切正常,但最近我收到来自 Google 的许可被拒绝返回。如果我退出 GR 并使用我的应用程序重新登录,一切都会重新开始。这让我相信
我想要的是最终得到类似的东西: public class InterleavedBufferedReader extends BufferedReader { ... } 并将其用作: Reader[
reader monad 有一个asks 函数,它的定义与reader 函数完全相同,为什么它作为一个单独的函数存在,与 的定义相同读者?为什么不总是使用阅读器? class Monad m => M
当使用csv模块读取文件时,有两种方法可以遍历csv.reader返回的生成器。 with open('foo.csv') as f: reader = csv.reader(f) r
我想在 Go 中按照 here 中的要求做同样的事情. 我正在解析一个巨大的日志文件,我需要逐行解析它。在每一行上,我将该行反序列化为一个结构。数据可能来自任何数据源(文件、网络等)。因此,我在我的函
我在golang的zlib/reader.go文件中找到了很多像r.(flate.Reader)这样的代码片段。这是什么意思? https://golang.org/src/compress/zlib
我正在 Spring MVC 中包装 Freemarker 模板加载器,如所述 here在 html 页面中进行默认转义。 所以,我需要用我的字符串包装来自 java.io.Reader 的内容,而不
为什么这个 PDF 在 Foxit Reader 而不是 Adobe Reader 中显示签名? 这是来自 Syncfusion PDF library 的代码用于生成它(另请参阅有关 signi
我有一个巨大的tbb::concurrent_unordered_map被多个(~60)线程同时“大量读取”。 我每天需要清除一次(完全清除或选择性清除)。在 tbb 中删除显然不是线程安全的实现,因
好像是 Hibernate.createClob(Reader reader, int length)在 3.6.x 版本中已弃用 它建议使用使用 LobHelper.createClob(Reade
这是我的实际解决方案 private def transpose[E, A](readers : Seq[Reader[E, A]]) : Reader[E, Seq[A]] = Read
DataReader[0].ToString() 和 (string)DataReader[0] 有区别吗? 我的猜测是,如果数据库类型不是字符串类型,(string)DataReader[0] 可能
我想制作一个 C# 程序来保存 pdf 和 djvu 文件的书签。如何从 AcroRd32/DjVuReader 进程中找出当前页码? 最佳答案 您可以通过 Adobe Acrobat 支持的 D
什么更好 var s = (string)reader[0] 或 var s = Convert.ToString(reader[0]) ? 最佳答案 我会说 reader.GetString(0
我对非官方阅读器 api 进行了大量研究,并筛选了其他问题,但没有一个完全满足我的要求。如果您知道文章 id 有据可查,如何分享文章,但如果您不知道 id,我想知道如何分享文章(即如何转换 url -
这是一个简单的示例,用于将 xml 文件读入 WebRowSet 对象,然后将数据从该对象加载到数据库。 import javax.sql.rowset.RowSetProvider; import
这样的转换对于任何仿函数都是可能的,不仅是Future: implicit class RichFunctorReader[F[_]: Functor, A, B](fr: F[Reader[A, B
我是一名优秀的程序员,十分优秀!