[英]Creating Activity feed using Web Sockets in Spring
我有一个仪表板,显示最近输入的用户以及从这些服务中获得的一些其他信息:
@JsonView(View.SurveyWithClients.class)
@RequestMapping(value="getData/{gender}",method=RequestMethod.GET)
public @ResponseBody List<Info> getTopUsers(@PathVariable("gender") char gender) {
List<Info> info=infoService.findByClient_GenderOrderByInfoResults(gender);
return info;
}
还有这个 :
@JsonView(View.SurveyWithClients.class)
@RequestMapping(value="getActivityFeed",method=RequestMethod.GET)
public @ResponseBody List<Info> getLatestActivity() {
return infoService.findTop5ByOrderBySubmittedDateDesc();
}
我目前正在做的是我对这两个端点进行ajax调用,并使数据显示在div中。 但是,我读到的一种更好的解决方案是使用Web套接字,以便实时更新视图。
是我需要传递的端点还是服务层? 代码的结构如何? 实现此目标的逻辑路径是什么? 我仅看到了将其用于聊天应用程序的示例,但我不知道如何使用此类计算和数据进行操作。 任何指导表示赞赏
如果您正在谈论供稿Web套接字的2路通道将是有道理的,如果您正在谈论1路也将是有道理的,但您需要记住,还有许多其他趋势可以使用http使用。
使用websocket时,您使用的是不同的协议(非HTTP),将使用HTTP建立连接,但是此后将为与HTTP协议分离的通信打开一个websocket,我认为这特别好,因为浏览器的执行能力有限并发HTTP请求。
我在春季的这篇“ 设计复杂通知”系统中提到了一种使用websocket和消息代理创建提要的方法。
您所需要做的就是包含websock依赖项
https://mvnrepository.com/artifact/org.springframework/spring-websocket/5.0.2.RELEASE
您还需要在Spring应用程序中配置websocket
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer{
@Autowired
private NotificationHandler notificationHandler;
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
System.out.println("handler registered for websocket");
registry.addHandler(notificationHandler, "/questions")//define the endpoint for the websocket with handler to all the messages
.setAllowedOrigins("*").withSockJS(); //allow CRSF
}
我的处理程序,用于推送到特定的客户端
@Component
public class NotificationHandler extends TextWebSocketHandler {
private Map<Integer, WebSocketSession> sessions = new ConcurrentHashMap<>();
private Map<String, List<Integer>> userToSessionMap = new ConcurrentHashMap<>();
@Autowired
private JwtTokenUtil jwtTokenUtil;
@Autowired
private NotificationService notificationService;
@Value("${jwt.header}")
private String tokenHeader;
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
sessions.put(Integer.valueOf(session.getId()), session);
}
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) {
System.out.println("Session Id: " + session.getId());
System.out.println("Session Id: " + session.getId());
System.out.println("Extracted session ID " + sessions.get(Integer.valueOf(session.getId())).getId());
String username = jwtTokenUtil.getUsernameFromToken(message.getPayload());
if(username == null || username.isEmpty()) {
return;
} else if(!userToSessionMap.containsKey(username)) {
userToSessionMap.put(username, new ArrayList<Integer>());
userToSessionMap.get(username).add(Integer.valueOf(session.getId()));
} else if(!userToSessionMap.get(username).contains(Integer.valueOf(session.getId()))) {
userToSessionMap.get(username).add(Integer.valueOf(session.getId()));
}
try {
sessions.get(Integer.valueOf(session.getId())).sendMessage(new TextMessage("new message recieved"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void sendMessageToUserSessions(User user, String message) {
Notification notification = notificationService.createNotification(user, message);
List<Integer> sessionsList = userToSessionMap.get(user.getUsername());
if(sessionsList == null || sessionsList.isEmpty())//no available sessions (makes no sense, need to check with UI)
return;
for(Integer sessionId: sessionsList) {
WebSocketSession session = sessions.get(sessionId);
if(session != null)
try {
session.sendMessage(new TextMessage(notification.toJsonString()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
};
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.