若依框架添加websocket服务监听日志文件变化并发送给前端

1 后端

1.1 添加websocket依赖

在ruoyi-framework模块pom.xml添加websocket依赖包

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

1.2 添加websocket配置

在ruoyi-framework模块的config下添加WebSocketConfig配置类

package com.ruoyi.framework.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

@Configuration
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

1.3 实现websocket服务

在ruoyi-admin添加一个包名handler,然后往里添加类WebSocketServer

package com.ruoyi.web.handler;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint("/websocket/{userId}")
@Component
@Slf4j
public class WebSocketServer {

    /**静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。*/
    private static int onlineCount = 0;
    /**concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。*/
    private static ConcurrentHashMap<String,WebSocketServer> webSocketMap = new ConcurrentHashMap<>();
    /**与某个客户端的连接会话,需要通过它来给客户端发送数据*/
    private Session session;
    /**接收userId*/
    private String userId="";


    /**
     * 连接建立成功调用的方法*/
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
        this.session = session;
        this.userId=userId;
        if(webSocketMap.containsKey(userId)){
            webSocketMap.remove(userId);
            webSocketMap.put(userId,this);
            //加入set中
        }else{
            webSocketMap.put(userId,this);
            //加入set中
            addOnlineCount();
            //在线数加1
        }

        log.info("用户连接:"+userId+",当前在线人数为:" + getOnlineCount());

        try {
            sendMessage("连接成功");
        } catch (IOException e) {
            log.error("用户:"+userId+",网络异常!!!!!!");
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {

        if(webSocketMap.containsKey(userId)){
            webSocketMap.remove(userId);
            //从set中删除
            subOnlineCount();
        }
        log.info("用户退出:"+userId+",当前在线人数为:" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息*/
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("用户消息:"+userId+",报文:"+message);
        //可以群发消息
        //消息保存到数据库、redis
    }

    /**
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("用户错误:"+this.userId+",原因:"+error.getMessage());
    }

    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }


    /**
     * 实现服务器主动推送
     */
    public void sendAllMessage(String message) throws IOException {
        ConcurrentHashMap.KeySetView<String, WebSocketServer> userIds = webSocketMap.keySet();
        for (String userId : userIds) {
            WebSocketServer webSocketServer = webSocketMap.get(userId);
            webSocketServer.session.getBasicRemote().sendText(message);
        }
    }

    /**
     * 发送自定义消息
     * */
    public static void sendInfo(String message,@PathParam("userId") String userId) throws IOException {
        log.info("发送消息到:"+userId+",报文:"+message);
        if(StringUtils.isNotBlank(userId)&&webSocketMap.containsKey(userId)){
            webSocketMap.get(userId).sendMessage(message);
        }else{
            log.error("用户"+userId+",不在线!");
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }
}

1.4 修改SecurityConfig

这是关键,不然客户端连接不上。找到ruoyi-framework下的SecurityConfig,放行websocket请求

.antMatchers("/websocket/**").permitAll()

修改后大概是这样子:
在这里插入图片描述

1.5 添加文件变化监听类

在ruoyi-admin与WebSocketServer 所在同意包名下添加文件变化监听类FileChangeWebSocketHandler

package com.ruoyi.web.handler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import javax.annotation.Resource;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Component
public class FileChangeWebSocketHandler {
    private final Path logFilePath = Paths.get("/var/log/syslog");
    private long lastSentPosition = 0; // 记录上次发送的位置

    private final WatchService watchService;

    @Resource
    private WebSocketServer webSocketServer;

    @Autowired
    public FileChangeWebSocketHandler() throws IOException {
        this.watchService = FileSystems.getDefault().newWatchService();
        logFilePath.getParent().register(watchService, StandardWatchEventKinds.ENTRY_MODIFY);
        watchFileChanges();
    }

    private void watchFileChanges() {
        new Thread(() -> {
            try {
                while (true) {
                    WatchKey key = watchService.take();
                    for (WatchEvent<?> event : key.pollEvents()) {
                        if (event.kind() == StandardWatchEventKinds.ENTRY_MODIFY) {
                            sendLogFileContent();
                        }
                    }
                    key.reset();
                }
            } catch (InterruptedException | IOException e) {
                e.printStackTrace();
            }
        }).start();
    }

    private void sendLogFileContent() throws IOException {
        long fileSize = Files.size(logFilePath);

        if (fileSize > lastSentPosition) {
            String incrementContent = readIncrementalContent();
            System.out.println("log file changed, context="+incrementContent);
            sendMessageToAllSessions(incrementContent);
            lastSentPosition = fileSize;
        }
    }

    private String readIncrementalContent() throws IOException {
        long fileSize = Files.size(logFilePath);
        long startPosition = lastSentPosition;
        long endPosition = fileSize;

        // 读取新增部分内容
        byte[] bytes = Files.readAllBytes(logFilePath);
        byte[] incrementBytes = Arrays.copyOfRange(bytes, (int) startPosition, (int) endPosition);

        return new String(incrementBytes, StandardCharsets.UTF_8);
    }

    public void sendMessageToAllSessions(String message) throws IOException {
        webSocketServer.sendAllMessage(message);
    }

    private List<WebSocketSession> getSessions() {
        // 获取当前所有的WebSocketSession
        // 这里可能需要维护一个会话列表
        // 可以根据具体情况自行实现
        return new ArrayList<>();
    }
}

说明,这里只是简单的指定了待监听文件的路径,实际应用中应该是通过外部传入的。

2 前端

2.1 代理配置

由于我前后端分离,服务端运行在另一台linux服务器上,而前端运行在本地,这就跨域了哈,这是需要配置开发环境下的跨域行为,在前端代码,打开.env.development文件,添加一个常量VUE_APP_WEBSOCKET_API = '/ws-api', 然后打开vue.config.js,添加websocket代理配置:

devServer: {
    host: '0.0.0.0',
    port: port,
    open: false,
    proxy: {
      // detail: https://cli.vuejs.org/config/#devserver-proxy
      [process.env.VUE_APP_BASE_API]: {
        target: `http://172.16.1.137:8080`,
        changeOrigin: true,
        pathRewrite: {
          ['^' + process.env.VUE_APP_BASE_API]: ''
        }
      },
      [process.env.VUE_APP_WEBSOCKET_API]: {
        target: `ws://172.16.1.137:8080`,
        changeOrigin: true,
        ws: true,
        pathRewrite: {
          ['^' + process.env.VUE_APP_WEBSOCKET_API]: ''
        }
      }
    },
    disableHostCheck: true
  }

这里也把http接口代理也配置了。

2.2 连接代码

在某个页面的created() 方法,连接websocket服务器,注意这里的url的请求路径“websocket”,名称要与服务器配置的名称保持一致。

created() {
    this.getList();

	const url = process.env.VUE_APP_WEBSOCKET_API + "/websocket/1500";
    let socket = new WebSocket(url);
    socket.onmessage = function(event) {
        console.log("Received file increment: " + event.data);
        // 处理接收到的文件增量内容,例如更新页面显示等
    };
  },

2.3 效果

启动服务端和前端,我们可以看到实时打印的每一行变化的文本

在这里插入图片描述

  • 24
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用框架提供的 WebSocket 功能来实现与客户端的实时通信。WebSocket 是一种在单个 TCP 连接上进行全双工通信的协议,能够实现实时的消息传递。 在大多数Web框架中,你可以通过以下步骤来使用WebSocket: 1. 导入 WebSocket 相关的库或模块,例如 `websocket` 或 `socket.io`。 2. 创建一个 WebSocket 服务器实例,并指定服务器的地址和端口。 3. 监听客户端的连接请求,并在连接建立时执行相应的操作。 4. 处理客户端发送的消息,并根据需要进行相应的处理。 5. 向客户端发送消息,以实现双向通信。 下面是一个简单的示例代码,演示了如何使用 WebSocket 框架来实现简单的聊天功能: ```python import websocket def on_message(ws, message): # 处理收到的消息 print("Received message:", message) def on_error(ws, error): # 处理错误信息 print("Error:", error) def on_close(ws): # 关闭连接时执行的操作 print("Connection closed") def on_open(ws): # 连接建立时执行的操作 print("Connection opened") # 发送消息到服务器 ws.send("Hello, server!") if __name__ == "__main__": # 创建 WebSocket 实例并指定服务器地址 ws = websocket.WebSocketApp("ws://localhost:8000", on_message=on_message, on_error=on_error, on_close=on_close) # 设置连接建立时的回调函数 ws.on_open = on_open # 启动 WebSocket 连接 ws.run_forever() ``` 以上代码是一个简单的 WebSocket 客户端示例,它使用 `websocket` 库来与服务器进行通信。你可以根据自己的需求进行修改和扩展。 希望这个示例能帮到你,如果你有更具体的问题或者需要进一步的帮助,请随时提问!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值