java - java中调用非静态消息传递函数

标签 java spring websocket messaging stomp

我正在尝试使用 STOMP 和 websockets 从应用程序中的任何位置发送消息。但是,我遇到了麻烦,因为由于方法内的“this.template”,我无法将“greet”方法设为静态。然后我无法调用该方法。我该如何解决这个问题?

这是我的 Controller 类:

@Controller

公共(public)类HelloController{

@Autowired
private SimpMessagingTemplate template;

@Autowired
public HelloController(SimpMessagingTemplate template) {
    this.template = template;
}

public HelloController() {

}

public static void replier(String reply) {
    greet(reply);
}

@RequestMapping(value="/hello", method=RequestMethod.POST)
public void greet(String greeting) {
    Greeting text = new  Greeting("Goodbye, " + greeting + "!");
    this.template.convertAndSend("/topic/greetings", text);
}

@RequestMapping(value="/", method=RequestMethod.GET)
public String index() {
    return "index";
}

@MessageMapping("/hello")
@SendTo("/queue/greetings")
public static Greeting greeting(HelloMessage message) throws Exception {
    System.out.println("Sending message...");
    beginRoute(message.getName());
    return new Greeting("Hello, " + message.getName() + "!");
}

@SendTo("/queue/informer")
public static Greeting beginRoute(String message) {
    Application.startBody(message);
    //System.out.println("Returning from second message!");
    return new Greeting("So long, " + message + "!");
}

replier方法中的greet(reply)调用无效,因为我无法对非静态方法进行静态调用。如何调用greet并接收发送的消息?

最佳答案

我不明白为什么您认为 greeting 需要是静态的。

我在 websocket documentation 上找到了这个:

@Controller
public class GreetingController {

    @MessageMapping("/greeting") {
    public String handle(String greeting) {
        return "[" + getTimestamp() + ": " + greeting;
    }
}

尝试使问候语不是静态的。如果您在使用非静态方法时遇到问题,请告诉我们问题是什么。

关于java - java中调用非静态消息传递函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24726767/

相关文章:

java - 在 Java 中实现定时器事件的最简单方法

java - 如何从 Apache CXF REST 服务返回 XML 并将其转换为 json?

Java JFrame ComboBox情况

java - Spring Cache - 如何捕获 except 参数中的异常?

python - 使用 python 连接到 flask websocket

java - Intellij 查找 .class 文件而不是 .java 文件

java - Spring 两种不同的应用上下文——属性占位符冲突

spring - 向多个 RabbitMQ 消费者提供相同的消息

spring - 无法通过 Kubernetes 入口访问 websocket

html - 将 Web 套接字限制为 LAN 网络