如何统计我REST API中的HTTP方法调用次数并将其存入数据库?

huangapple go评论66阅读模式
英文:

How can I count the number of HTTP method calls in my REST API and put it into a database?

问题

我有一个简单的程序,应该从GitHub的API中获取用户,并且我想计算调用该方法的次数。
这是我的REST控制器,其中有一个GET方法(需要计数的方法):

@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 和 REQUEST_COUNT。
但是该方法实际上什么都不做,我的数据库表保持不变。

public void insertRecord(String login) {
    // 这部分检查数据库中是否已经有这样的登录名
    String sql = "select * from calls where LOGIN = ?";
    PreparedStatement preparedStatement;
    ResultSet resultSet;
    try {
        preparedStatement = getConnection().prepareStatement(sql);
        preparedStatement.setString(1, login);
        resultSet = preparedStatement.executeQuery();
        // 如果有结果 - 我试图将 REQUEST_COUNT 列的值加 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("无法将记录插入数据库。");
                e.printStackTrace();
            }
        // 如果没有结果 - 我想插入新记录。
        } 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("无法将记录插入数据库。");
                e.printStackTrace();
            }
        }

    } catch (SQLException e) {
        logger.error("操作失败。");
        e.printStackTrace();
    }
}

日志消息也没有被打印出来,就好像该方法完全被忽略了。

请帮助。

英文:

I have a simple program that is supposed to get a user from github's API and I want to count the times the method is called.
Here is my REST Controller with a GET method (that's the method to be counted):

@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);
    }
}

My program works (more or less) as it's supposed to, BUT .insertRecord() method does not work at all. It basically does nothing. The method SHOULD check if the database already has a user of the given login. If yes - then it should proceed to update the record and increment the REQUEST_COUNT number by 1. If no - then it should create a new record of a given login and REQUEST_COUNT as 1. The table in my database has only two column - LOGIN and REUQEST_COUNT.
But that method literally does nothing, the table in my database remains untouched.

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();
        }
    }

No Logger's messages are printed either, it's as if the method was simply completely ignored.

Please, help.

答案1

得分: 1

因为您没有调用 updatePreparedStatement.executeUpdate()

只有在您调用 executeUpdate() 后,SQL 语句才会生效。

英文:

Because you are not calling updatePreparedStatement.executeUpdate() !

The sql will only take effetc after you call executeUpdate().

答案2

得分: 1

你可以添加一个在端点执行之前/之后执行的过滤器。在该特定过滤器中,你还可以追踪执行的端点并为任何特定端点采取适当的操作。

英文:

You can put a filter that will execute before/after the endpoint executed. And in that particular filter, you can also track which endpoint is executed and take appropriate action for any specific endpoint.

huangapple
  • 本文由 发表于 2020年8月31日 03:35:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/63661419.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定