[英]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.