asp.net - 增加计数器但随着延迟减少

标签 asp.net vb.net caching redis

我想保留一个计数器来查看有多少用户正在调用 Web 服务。 Web 服务几乎在一秒钟内完成。我可以在开始时增加一个变量并在最后减少,但这不是我想要的。

我需要在开始时增加变量并在 3 秒后减少计数。我考虑过使用缓存过期,但一秒钟内会有超过 1000 次调用,我不想给服务器或内存增加额外的负载。我也知道像 (hangfire) 这样的即发即弃方法可以工作,但在那种情况下,我需要在类中为每个请求运行计时器。

此外,此方法必须是线程安全的。我最近使用 Redis,所以如果存在这种功能,它可以成为我的解决方案。我也喜欢它。

目前我做的是: 以创建日期为开头将记录写入数据库 之后删除超过 2 秒的记录 运行程序

但这会加载数据库,我想不出一个简单的解决方案。

有什么想法吗? 谢谢。

编辑: 我制作了以下示例。继续按增量按钮,大约 90.000 你会在行中得到“对象变量未设置”错误:

Cache("x") = CInt(Cache("x").ToString) + 1

...

Imports Microsoft.VisualBasic
Imports System.Threading
Imports System.Threading.Tasks
Imports System.Web.Hosting

Partial Class _Default
    Inherits System.Web.UI.Page

    Protected Sub cmdIncrement_Click(sender As Object, e As EventArgs) Handles cmdIncrement.Click
        For i As Integer = 1 To 10000
            If Cache("x") Is Nothing Then Cache("x") = 0
            Cache("x") = CInt(Cache("x").ToString) + 1
            fireit()
        Next
        getvalue()
    End Sub
    Protected Sub cmdRefresh_Click(sender As Object, e As EventArgs) Handles cmdRefresh.Click
        getvalue()
    End Sub
    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        getvalue()
    End Sub
    Protected Sub getvalue()
        If Cache("x") Is Nothing Then Cache("x") = 0
        Label1.Text = Cache("x").ToString & " - " & Now.ToString
    End Sub
    Protected Sub fireit()
        HostingEnvironment.QueueBackgroundWorkItem(Function(token) DecrementMyVariable("aaa", token))
    End Sub

    Protected Shared Async Function DecrementMyVariable(text As String, token As CancellationToken) As Task(Of String)
        Await Task.Delay(5000)
        Dim x As Integer = CInt(HttpRuntime.Cache("x").ToString)
        HttpRuntime.Cache("x") = x - 1
        Return "aaa"
    End Function

End Class

最佳答案

您只想将每次调用该服务的日期和时间存储到日志中。然后,您可以在给定的时间段内绘制它。将详细信息保存到 CSV 文件,您只需在 Excel 中查看数据即可。

您可以将其存储到数据库中,然后查询数据库以查找最近三秒内的所有调用。

关于asp.net - 增加计数器但随着延迟减少,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28947946/

相关文章:

asp.net - 在 ASP.Core 中找不到 WindowsImpersonationContext 和 Impersonate()

asp.net - 使用 dotnet-buildpack 将 ASP.NET 5 应用程序部署到 Heroku 时出错

asp.net - EF Core 2.1项目Add-Migration NullReferenceException

c# - 如何在我的解决方案中使用来自其他项目的 Web Api 项目?

VB.Net Switch 语句,在每种情况下都包含代码段

.net - 如何对组合框中的数据进行排序

vb.net - 如何从字体文件名获取字体属性?

javascript - 使用 react js 和 webpack 开发的 Web 应用程序的缓存问题

c# - 如何检查 Page.Cache 的大小?

r - 有没有办法生成 rmarkdown 文档的缓存版本,然后直接从缓存中生成多个输出?