有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java电报机器人(新线程中的新更新)和电报机器人SpringBootStarter


我编写了一个LongPolling机器人,它一次只进行一次更新
我希望它能够通过多线程处理2个或更多的更新
这里是我的意思。我在性能优化(Python电报机器人)一文中找到了这个例子

Example: You're running the Echobot and two users (User A and User B) send a message to the bot at the same time. Maybe User A was a bit quicker, so his request arrives first, in the form of an Update object (Update A). The Dispatcher checks the Update and decides it should be handled by the handler with the callback function named echo. At the same time, the Update of User B arrives (Update B). But the Dispatcher is not finished with Update A. It calls the echo function with Update A, which sends a reply to User A. Sending a reply takes some time (see Server location), and Update B remains untouched during that time. Only after the echo function finishes for Update A, the Dispatcher repeats the same process for Update B.

在本文中,为了解决这类问题,python电报库提供了一种在单独线程中显式运行回调函数(或任何其他函数)的方法
能给我解释一下如何使用java吗???
下面是我的代码部分:


机器人

@Component   
public class SenderBot extends TelegramLongPollingBot {

private static final String BOT_TOKEN = "token";
private static final String BOT_NAME = "bot_name";

static {
    ApiContextInitializer.init();
}

@Override
public void onUpdateReceived(Update update) {

    if (update.hasMessage()) {
    ...
    some code
    ...
    }
}
}



SpringBootApp

@SpringBootApplication
public class SenderBotApplication {
public static void main(String[] args) {
    SpringApplication.run(SenderBot.class, args);
    }
}

如果有人知道没有多线程的另一种方法-告诉我怎么做
我将非常感谢任何帮助和例子


共 (1) 个答案

  1. # 1 楼答案

    我找到了解决办法

    @Override
        public void onUpdateReceived(Update update) {
    
            new Thread(new Runnable() {
                @Override
                public void run() {
                    if (update.hasMessage()) {
                    // code goes here.
                    }
                  }
           }).start
    }
    

    这段代码可以与许多用户同时使用。 但我不知道这个解决方案是否正确