从后端获取计数器的当前值:REST API

问题描述

我想在后端(REST API)中实现一个简单的路由,当我第一次点击端点(比如*{ margin: 0; padding: 0; Box-sizing: border-Box; } @font-face{ src: url(/fonts/Coiny-Regular.ttf); font-family: Coiny; } body,html{ background-color: rgb(230,230,230); font-family: Arial,Helvetica,sans-serif; } .Board{ display: flex; align-items: center; text-align: center; justify-content: left; } .panel{ background-color: white; width: 450px; height: 650px; border-radius: 2rem; margin-left: 40px; margin-top: 30px; Box-shadow: 7px 7px 7px 7px rgba(202,202,0.3); } .right-panel{ background-color: white; width: 950px; height: 650px; border-radius: 2rem; margin-left: 40px; margin-top: 30px; Box-shadow: 7px 7px 7px 7px rgba(202,0.3); } .user h3{ background-color: whitesmoke; text-align: start; padding: 20px; font-size: 20px; border-radius: 2rem; font-family: Coiny,cursive; margin: 20px; } )时,我返回计数器的初始值和 开始计数器的连续递增过程,这样每当我再次到达端点时,我都会获取计数器的当前值。像这样

/api/counter

我怎样才能做到这一点?为此我需要不同的路线吗?

PS:我的问题不完全是一个计数器,但我用这个非常相似的问题来表达它。

解决方法

当 API 被命中时,如果您的计数器变量是在本地范围内定义的,它将被重置。

您可以通过在全局范围内定义变量来使其工作,但此方法的另一个问题是如果您的应用程序崩溃或重新启动,那么您的计数器将丢失。

为此,您可以采用以下任何一种方法

  1. 利用文件系统:当您的 API 命中时,从文件中读取计数器值,将其递增并更新到文件中并发送回响应。这种方法的缺点是,它会增加文件 IO 的开销。
  2. 使用任何数据库:如果数据库支持,您可以使用增量功能($inc for mongodb while field = field + 1 in MySQL)。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...