Home  >  Article  >  Java  >  How to use Java to write the user real-time online function of the CMS system

How to use Java to write the user real-time online function of the CMS system

PHPz
PHPzOriginal
2023-08-25 20:48:231290browse

How to use Java to write the user real-time online function of the CMS system

How to use Java to write the user real-time online function of the CMS system

With the rapid development of the Internet, content management systems (CMS) have become the core of many websites and applications. core. In order to provide a better user experience, real-time online functionality is an important component. This article will introduce how to use Java to write the user real-time online function of the CMS system and provide code examples.

1. Introduce dependencies

First, add the following dependencies in the pom.xml file of the Java project:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-websocket</artifactId>
    </dependency>
</dependencies>

This will introduce Spring Boot's WebSocket support.

2. Configure WebSocket

Add the following configuration in the Spring Boot configuration file (such as application.properties):

# WebSocket配置
spring.mvc.websocket.enabled=true
spring.messages.suffix=message

This will enable the WebSocket function and configure the message The suffix is ​​"message".

3. Create a WebSocket processor

Create a WebSocket processor to handle WebSocket connections and messages from the client. This can be achieved by writing a class that implements the WebSocketHandler interface.

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;

@Component
public class CMSWebSocketHandler implements WebSocketHandler {

    private static final Map<String, WebSocketSession> SESSIONS = new HashMap<>();

    // 连接建立时触发
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        SESSIONS.put(session.getId(), session);
    }

    // 收到消息时触发(此处假设消息为用户ID)
    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
        String userId = message.getPayload().toString();
        // 处理用户上线逻辑
        // ...
    }

    // 连接关闭时触发
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        SESSIONS.remove(session.getId());
    }

    // 发生错误时触发
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        // 处理错误逻辑
        // ...
    }
}

In the above code, we use a static Map to store all connected WebSocket sessions. When the connection is established, the session is added to the Map; when the connection is closed, it is removed from the Map. By overriding the handleMessage method, messages received from the client can be processed.

4. Configure the WebSocket processor

In the Spring Boot configuration class, configure the WebSocket processor:

import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    private final CMSWebSocketHandler cmsWebSocketHandler;

    public WebSocketConfig(CMSWebSocketHandler cmsWebSocketHandler) {
        this.cmsWebSocketHandler = cmsWebSocketHandler;
    }

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(cmsWebSocketHandler, "/ws").setAllowedOrigins("*");
    }
}

In the above code, we register the WebSocket processor as A WebSocket handler, mapped to the "/ws" path. Allow WebSocket connections from any origin by setting setAllowedOrigins("*").

5. Front-end integration

In the front-end page, use JavaScript or other related technologies to establish a connection with the back-end through WebSocket and pass the user ID.

const socket = new WebSocket("ws://localhost:8080/ws");
const userId = "12345";
socket.onopen = () => {
    socket.send(userId);
};

socket.onclose = () => {
    // 连接关闭逻辑
};

As shown in the above code, when the WebSocket connection is established, the user ID is sent through socket.send(userId).

6. Real-time online function implementation

In the CMS system, the real-time online function can be realized through the afterConnectionEstablished and afterConnectionClosed methods in the WebSocket processor.

// 连接建立时触发
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
    SESSIONS.put(session.getId(), session);
    // 用户上线逻辑
    String userId = getUserIdFromSession(session);
    // 处理用户上线逻辑
}

// 连接关闭时触发
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
    SESSIONS.remove(session.getId());
    // 用户下线逻辑
    String userId = getUserIdFromSession(session);
    // 处理用户下线逻辑
}

// 辅助方法:从会话中获取用户ID
private String getUserIdFromSession(WebSocketSession session) {
    Map<String, Object> attributes = session.getAttributes();
    // 从attributes中获取用户ID
    // ...
}

When a user connection is established, put the session into the SESSIONS Map, obtain the user ID from the session, and perform corresponding user online logic processing. When the user connection is closed, the session is removed from the SESSIONS Map and the corresponding user offline logic is processed.

7. Summary

This article introduces how to use Java to write the user real-time online function of the CMS system. By introducing dependencies, configuring WebSocket, creating WebSocket processors and front-end integration, we can realize the user's real-time online function and perform corresponding processing. In actual applications, further functional expansion and optimization can be carried out according to actual needs.

The above is an introduction on how to use Java to write the user real-time online function of the CMS system. I hope it will be helpful to you.

The above is the detailed content of How to use Java to write the user real-time online function of the CMS system. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn