如何从Spring @Service bean获取/修改所有用户会话(使用Struts mvc)?

问题描述 投票:0回答:1

我正在实施一个通知服务,通知所有用户(有活动会话)有关新通知的信息。由于此Web应用程序使用Struts MVC(不是单页面应用程序),因此使用Web Socket似乎不合适,因为每个页面加载都需要新的WS连接。相反,我的方法是每分钟运行一次Spring @Service以使用“Unread_Notification_Count”更新所有活动用户会话,因此每个页面加载可以简单地检查用户的会话以获取此值并相应地更改显示(消除每个数据库的查询)页面加载)。

我有两个问题:1)这是解决此问题的最佳方法,因为我在Spring文档中读到,您应该避免直接更改用户会话。 2)如果此方法为“ok”,那么如何访问每个用户会话以插入/更改“Unread_Notification_Count”值?

@Service("notifySessionsService")
public class NotifySessionsServiceImpl implements NotifySessionsService {

    @Autowired
    private transient SessionRegistry sessionRegistry;

    @Override
    public void updateUnReadNotificationCount() {

        for (Object principal : sessionRegistry.getAllPrincipals()) {
            List<SessionInformation> sessionInformationList = sessionRegistry.getAllSessions(principal, false);
            for (SessionInformation sessionInformation : sessionInformationList) {
                System.out.println("Updating session for user: "  + ((User)principal).getUsername() + ", sessionId: " + sessionInformation.getSessionId());
                // [Get users notification count here]
                // [Put in session, e.g. session.put("Unread_Notification_Count", count)]
            }
        }

    }

    public void setSessionRegistry(SessionRegistry sessionRegistry) {
        this.sessionRegistry = sessionRegistry;
    }
}
java spring session struts
1个回答
0
投票

安德鲁感谢你的想法。我最终选择了javascript / client pull版本。只是为了关闭我的代码最终像下面的代码。客户端每5分钟检查一次通知(基于时间而不是计时器)

var queryNotificationsEvery = 5; // in minutes

function startNotificationService(appUserId) {
    // Check each minute to see if we need to query for notifications
    setInterval(queryNotificationCount, 1000 * 60, appUserId)
}

function queryNotificationCount(appUserId) {

    var currentMinute = new Date().getMinutes();
    if (currentMinute % queryNotificationsEvery === 0) {

        // Query server via AJAX
        var notificationCount = queryServer(appUserId);

        // Change UI
        changeUINotifications(notificationCount);
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.