Spring WebSocket 从服务器发送多个对值消息
Spring WebSocket send multiple pair-value message from server
我一直在研究Spring WebSocket example。我想创建这样的应用程序来交换来自 db<->server<->client 的信息。我已经创建了我自己的 bean,它将对 db 进行查询,在本例中它是 AnimalBean
。这是应用程序的控制器:
@Controller
public class GreetingController {
@MessageMapping("/hello")
@SendTo("/topic/greetings")
public Greeting greeting(HelloMessage message, AnimalBean ab) throws Exception {
return new Greeting(ab.getCows() + "\t" + new Date() + "\t" + message.getName());
}
}
因为我想向客户发送不同数量的动物,如 ab.getCows()
或 ab.getRabbits()
等,我想知道是否可以在一条 JSON 消息中发送它所以示例消息如下所示:
{"cows":"4", "rabbits":"60"}
能否实现,最简单的方法是什么?
假设 AnimalBean 是您的 DAO Bean。更新后的 class 看起来像。
@Controller
public class GreetingController {
@Autowired
private AnimalBean ab;
@MessageMapping("/hello")
@SendTo("/topic/greetings")
public AnimalInfogreeting(HelloMessage message) throws Exception {
return new AnimalInfo(ab.getCows(), ab.getRabbits());
}
}
创建 POJO class。
public class AnimalInfo{
private int cows;
pirvate int rabbits;
public AnimalInfo(int cows, int rabbits){
this.cows= cows;
this.rabbits =rabbits;
}
//getters and setters
}
我一直在研究Spring WebSocket example。我想创建这样的应用程序来交换来自 db<->server<->client 的信息。我已经创建了我自己的 bean,它将对 db 进行查询,在本例中它是 AnimalBean
。这是应用程序的控制器:
@Controller
public class GreetingController {
@MessageMapping("/hello")
@SendTo("/topic/greetings")
public Greeting greeting(HelloMessage message, AnimalBean ab) throws Exception {
return new Greeting(ab.getCows() + "\t" + new Date() + "\t" + message.getName());
}
}
因为我想向客户发送不同数量的动物,如 ab.getCows()
或 ab.getRabbits()
等,我想知道是否可以在一条 JSON 消息中发送它所以示例消息如下所示:
{"cows":"4", "rabbits":"60"}
能否实现,最简单的方法是什么?
假设 AnimalBean 是您的 DAO Bean。更新后的 class 看起来像。
@Controller
public class GreetingController {
@Autowired
private AnimalBean ab;
@MessageMapping("/hello")
@SendTo("/topic/greetings")
public AnimalInfogreeting(HelloMessage message) throws Exception {
return new AnimalInfo(ab.getCows(), ab.getRabbits());
}
}
创建 POJO class。
public class AnimalInfo{
private int cows;
pirvate int rabbits;
public AnimalInfo(int cows, int rabbits){
this.cows= cows;
this.rabbits =rabbits;
}
//getters and setters
}