In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article introduces the knowledge of "how to output spring boot integrated WebSocket logs to web pages in real time". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Preface
In fact, this paper uses the webSocket module of spring boot to provide the server side of stomp, the front end uses stomp.min.js as the client side of stomp, uses sockjs to link, the front end subscribes to the messages of the back-end log endpoint, and the back-end is pushed in real time to achieve the purpose of real-time output of the log to the web page. The effect is as follows
First of all, learn about stomp.
STOMP, or Simple (or Streaming) Text Orientated Messaging Protocol, a simple (streaming) text-oriented message protocol, provides an interoperable connection format that allows STOMP clients to interact with any STOMP message broker (Broker). Because of its simple design and easy to develop client, STOMP protocol has been widely used in many languages and platforms.
The predecessor of STOMP protocol is TTMP protocol (a simple text-based protocol), which is designed for messaging middleware.
STOMP is a very simple and easy to implement protocol, and its design is inspired by the simplicity of HTTP. Although it may be difficult to implement STOMP protocol on the server side, it is easy to implement it on the client side. For example, you can use Telnet to log in to any STOMP agent and interact with the STOMP agent.
The following are the specific steps, mainly the acquisition of log information and the push of log information, not to mention the code
one。 Spring boot websocket is introduced to depend on org.springframework.boot spring-boot-starter-websocket II. New log message entity / * Created by kl on 2017-10-9. * Content: log message entity. Note that in order to reduce the length, the get,set code * / public class LoggerMessage {private String body; private String timest private String threadName; private String className; private String level; public LoggerMessage (String body, String timestamp, String threadName, String className, String level) {this.body = body is omitted here. This.timestamp = timest this.threadName = threadName; this.className = className; this.level = level;} public LoggerMessage () {}} three. Create a blocking queue
As a temporary carrier of logs output by the log system
Public class LoggerQueue {/ / queue size public static final int QUEUE_MAX_SIZE = 10000; private static LoggerQueue alarmMessageQueue = new LoggerQueue (); / / blocking queue private BlockingQueueblockingQueue = new LinkedBlockingQueue (QUEUE_MAX_SIZE); private LoggerQueue () {} public static LoggerQueue getInstance () {return alarmMessageQueue } / * message queuing * @ param log * @ return * / public boolean push (LoggerMessage log) {return this.blockingQueue.add (log); / / throw an exception when the queue is full, without blocking} / * message dequeuing * @ return * / public LoggerMessage poll () {LoggerMessage result = null Try {result = this.blockingQueue.take ();} catch (InterruptedException e) {e.printStackTrace ();} return result;}} four. Get the log of logback and plug it into the log queue
1. Define Logfilter intercept output log
Public class LogFilter extends Filter {@ Override public FilterReply decide (ILoggingEvent event) {LoggerMessage loggerMessage = new LoggerMessage (event.getMessage (), DateFormat.getDateTimeInstance () .format (new Date (event.getTimeStamp (), event.getThreadName (), event.getLoggerName (), event.getLevel () .levelStr) LoggerQueue.getInstance () .push (loggerMessage); return FilterReply.ACCEPT;}
two。 Configure logback.xml and add our custom filter
${CONSOLE_LOG_PATTERN} utf8 V. Configure the WebSocket message broker endpoint, that is, the stomp server @ Configurationpublic class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {@ Override public void registerStompEndpoints (StompEndpointRegistry registry) {registry.addEndpoint ("/ websocket") .setAllowedOrigins ("http://localhost:8976") .withSockJS ();}}
Note: for the sake of connection security, the source address of the allowed connection set by setAllowedOrigins will report 403 if the connection is sent under an address other than this configuration. Furthermore, you can use addInterceptors to set an interceptor to do relevant authentication operations.
six。 Start the class, enable the webSocket message broker function, and push the log information @ SpringBootApplication@EnableScheduling@EnableWebSocketMessageBrokerpublic class WebsocketApplication {private Logger logger = LoggerFactory.getLogger (WebsocketApplication.class); public static void main (String [] args) {SpringApplication.run (WebsocketApplication.class, args);} @ Autowired private SimpMessagingTemplate messagingTemplate; int info=1 @ Scheduled (fixedRate = 1000) public void outputLogger () {logger.info ("Test Log output" + info++);} / * push logs to / topic/pullLogger * / @ PostConstruct public void pushLogger () {ExecutorService executorService=Executors.newFixedThreadPool (2) Runnable runnable=new Runnable () {@ Override public void run () {while (true) {try {LoggerMessage log = LoggerQueue.getInstance () .poll () If (logically invalid null) {if (messagingTemplet plates null) messagingTemplate.convertAndSend ("/ topic/pullLogger", log) }} catch (Exception e) {e.printStackTrace () ExecutorService.submit (runnable); executorService.submit (runnable) }} Seven. Html page, connect to stomp server, subscribe to / topic/pullLogger message, display log information WebSocket Logger close log var stompClient= null; $(document) .ready (function () {openSocket ();}); function openSocket () {if (stompClient==null) {var socket = new SockJS ('http://localhost:8084/websocket?token=kl');) StompClient = Stomp.over (socket); stompClient.connect ({token: "kl"}, function (frame) {stompClient.subscribe ('/ topic/pullLogger', function (event) {var content=JSON.parse (event.body)) $("# log-container div") .append (content.timestamp + "" + content.level+ "--[" + content.threadName+ "]" + content.className+ ":" + content.body) .append (""); $("# log-container") .scrollTop ($("# log-container div"). Height ()-$("# log-container"). Height ()) }, {token: "kltoen"});})} function closeSocket () {if (stompClient! = null) {stompClient.disconnect (); stompClient=null This is the end of "the method of spring boot integrating WebSocket logs for real-time output to web pages". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.