Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
435 views
in Technique[技术] by (71.8m points)

spring - Rest API send websocket message as well as response entity

I'm using spring boot and I was wondering if I can create a REST API that also sends a message to a websocket channel? so anyone subscribed to it can get it. Since it's a rest api, there would also be a response entity when it's done as well. If so, can i see an example of how that would work? i've been googling everywhere.

question from:https://stackoverflow.com/questions/65713233/rest-api-send-websocket-message-as-well-as-response-entity

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Good starting points to build a Spring Boot application with Websocket support are

To determine connected users you can use SimpUserRegistry bean and to send messages to them you can use SimpMessagingTemplate, for example:

@RestController
public class ApiController {

    private final SimpMessagingTemplate template;
    private final SimpUserRegistry userRegistry;

    public ApiController(SimpMessagingTemplate template, SimpUserRegistry userRegistry) {
        this.template = template;
        this.userRegistry = userRegistry;
    }

    @PostMapping("/api/users/{username}/send")
    public ResponseEntity<?> sendMessage(@RequestBody Message message, @PathVariable String username) {
        Set<SimpUser> users = userRegistry.getUsers();
        if (users.stream().anyMatch(simpUser -> simpUser.getName().equals(username))) {
            template.convertAndSendToUser(username, "/messages", message);
            return ResponseEntity.noContent().build();
        } else {
            return ResponseEntity.notFound().build();
        }
    }
}

You can check my minimal example of working Websockets demo application.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...