[英]How can I count the number of HTTP method calls in my REST API and put it into a database?
我有一个简单的程序,应该从 github 的 API 获取用户,我想计算调用该方法的次数。 这是我的带有 GET 方法的 REST 控制器(这是要计算的方法):
@RestController
@RequestMapping("/api/v1")
public class UserController {
private UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
@GetMapping("/user/info/{login}")
public User getUser(@PathVariable String login) throws IOException {
userService.insertRecord(login);
return userService.fetchUser(login);
}
}
我的程序按预期工作(或多或少),但 .insertRecord() 方法根本不起作用。 它基本上什么都不做。 该方法应该检查数据库是否已经有给定登录的用户。 如果是 - 那么它应该继续更新记录并将 REQUEST_COUNT 号增加 1。如果不是 - 那么它应该创建一个给定登录的新记录,REQUEST_COUNT 为 1。我的数据库中的表只有两列 - LOGIN 和REUQEST_COUNT 个。 但该方法实际上什么也没做,我数据库中的表保持不变。
public void insertRecord(String login) {
//this part checks if there is a login like that in the database already
String sql = "select * from calls where LOGIN = ?";
PreparedStatement preparedStatement;
ResultSet resultSet;
try {
preparedStatement = getConnection().prepareStatement(sql);
preparedStatement.setString(1, login);
resultSet = preparedStatement.executeQuery();
//if there's a result - I am trying to increment the value of REQUEST_COUNT column by 1.
if (resultSet.next()) {
String updateSql = "update calls set REQUEST_COUNT = REQUEST_COUNT + 1 where login = ?";
PreparedStatement updatePreparedStatement;
try {
updatePreparedStatement = getConnection().prepareStatement(updateSql);
updatePreparedStatement.setString(1, login);
} catch (SQLException e) {
logger.error("Could not insert a record into the database.");
e.printStackTrace();
}
//if there is no result - I want to insert a new record.
} else {
String insertSql = "insert into calls (LOGIN, REQUEST_COUNT) values (?, ?)";
try (final PreparedStatement insertPreparedStatement = getConnection().prepareStatement(insertSql)) {
insertPreparedStatement.setString(1, login);
insertPreparedStatement.setInt(2, 1);
} catch (SQLException e) {
logger.error("Could not insert a record into the database.");
e.printStackTrace();
}
}
} catch (SQLException e) {
logger.error("Operation failed.");
e.printStackTrace();
}
}
也不会打印 Logger 的消息,就好像该方法被完全忽略了一样。
请帮忙。
因为您没有调用updatePreparedStatement.executeUpdate()
!
在您调用executeUpdate()
后,sql 只会采用 effetc 。
您可以放置一个过滤器,该过滤器将在端点执行之前/之后执行。 在该特定过滤器中,您还可以跟踪执行了哪个端点并针对任何特定端点采取适当的操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.