向前端实时推送服务端日志springboot+websocket

自己参考其他博客搭建的一个简单websocket日志推送框架,集成到项目中也比较方便

1.pom.xml导入依赖

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

2.application.properties配置

server.port=8087
spring.resources.static-locations=classpath:/templates/
#spring.thymeleaf.cache=false
spring.mvc.view.prefix=/
spring.mvc.view.suffix=.html

3.添加以下三个类

第一个类的log路径需要改成自己要显示的log路径

@ServerEndpoint("/log")
@Component
public class LogWebSocketHandle {

    private Process process;
    private InputStream inputStream;

    /**
     * 新的WebSocket请求开启
     */
    @OnOpen
    public void onOpen(Session session) {
        try {
            // 执行tail -f命令,填写自己的log路径
            process = Runtime.getRuntime().exec("tail -100f xxx.log");
            inputStream = process.getInputStream();

            // 一定要启动新的线程,防止InputStream阻塞处理WebSocket的线程
            TailLogThread thread = new TailLogThread(inputStream, session);
            thread.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * WebSocket请求关闭
     */
    @OnClose
    public void onClose() {
        try {
            if (inputStream != null)
                inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (process != null)
            process.destroy();
    }

    @OnError
    public void onError(Throwable thr) {
        thr.printStackTrace();
    }
}

 

public class TailLogThread extends Thread {

    private BufferedReader reader;
    private Session session;

    public TailLogThread(InputStream in, Session session) {
        this.reader = new BufferedReader(new InputStreamReader(in));
        this.session = session;

    }

    @Override
    public void run() {
        String line;
        try {
            while ((line = reader.readLine()) != null) {
                // 将实时日志通过WebSocket发送给客户端,给每一行添加一个HTML换行
                session.getBasicRemote().sendText(line + "<br>");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
@Configuration
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

4.启动类

@SpringBootApplication
@Controller
public class DemoApplication {

    public static void main(String[] args) {

        SpringApplication.run(DemoApplication.class, args);
    }

    /**
     * 登陆界面
     */
    @GetMapping("/")
    public ModelAndView login() {
        return new ModelAndView("index");
    }

}

5.前端界面(需要修改为自己的websocket路径)

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>tail log</title>
    <script src="//cdn.bootcss.com/jquery/2.1.4/jquery.js"></script>
</head>
<body>
<div id="log-container" style="height: 450px; overflow-y: scroll; background: #333; color: #aaa; padding: 10px;">
    <div>
    </div>
</div>
</body>
<script>
    $(document).ready(function () {
        // 指定websocket路径
        var websocket = new WebSocket('ws://localhost:8087/log');
        websocket.onmessage = function (event) {
            // 接收服务端的实时日志并添加到HTML页面中
            $("#log-container div").append(event.data);
            // 滚动条滚动到最低部
            $("#log-container").scrollTop($("#log-container div").height() - $("#log-container").height());
        };
    });
</script>
</body>
</html>

结果展示如下: 

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
以下是一个基于 Spring Boot、WebSocket 和 Vue 实现后端向前端实时推送数据的代码示例: 1. 后端代码 ``` @Controller public class WebSocketController { private final WebSocketService webSocketService; @Autowired public WebSocketController(WebSocketService webSocketService) { this.webSocketService = webSocketService; } @GetMapping("/") public String index() { return "index"; } @MessageMapping("/send") public void send(String message) { webSocketService.sendAll(message); } @Bean public ServerEndpointExporter serverEndpointExporter() { return new ServerEndpointExporter(); } } ``` ``` @Service public class WebSocketService { private final List<Session> sessions = new CopyOnWriteArrayList<>(); public void add(Session session) { sessions.add(session); } public void remove(Session session) { sessions.remove(session); } public void sendAll(String message) { sessions.forEach(session -> { try { session.getBasicRemote().sendText(message); } catch (IOException e) { e.printStackTrace(); } }); } } ``` 2. 前端代码 ``` <template> <div> <h1>Real-time data:</h1> <ul> <li v-for="(data, index) in dataList" :key="index">{{ data }}</li> </ul> <input type="text" v-model="message" /> <button @click="send">Send</button> </div> </template> <script> export default { data() { return { dataList: [], message: '' } }, mounted() { const ws = new WebSocket('ws://localhost:8080/ws'); ws.onmessage = (event) => { this.dataList.push(event.data); }; ws.onclose = () => { console.log('Connection closed'); }; }, methods: { send() { const ws = new WebSocket('ws://localhost:8080/ws'); ws.onopen = () => { ws.send(this.message); ws.close(); }; } } } </script> ``` 在这个示例中,我们首先创建了一个 WebSocket 服务端,其中包含了一个用于处理客户端发送的消息的方法 send(),它会将接收到的消息发送给所有连接上的客户端。我们还创建了一个 WebSocketService,用于管理客户端连接和消息发送。 在前端,我们通过 Vue 的 mounted 生命周期创建了一个 WebSocket 连接,并在每次接收到服务器发来的消息时将其添加到一个数据列表中,然后在模板中通过 v-for 渲染出来。我们还在模板中添加了一个文本框和一个按钮,用于向服务器发送消息。当用户点击按钮时,我们创建一个新的 WebSocket 连接,并在连接打开后发送用户输入的消息,然后立即关闭连接。 要注意的是,我们在前端中创建了两个 WebSocket 连接,一个用于接收服务器推送的数据,另一个用于向服务器发送数据。这是因为 WebSocket 是全双工通信,可以同时进行发送和接收操作。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值