💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
ChannelInterceptor 拦截器拦截 ws 协议的请求/响应(`send/subscribe`),不拦截 http 协议的请求/响应。 [TOC] # 1. ChannelInterceptor使用步骤 拦截器使用步骤如下: **1. 实现拦截器接口** ```java //方法调用顺序:preSend -> postSend -> afterSendCompletion public class SocketChannelInterceptor implements ChannelInterceptor { /** * 消息发送到目标方法之前被调用 * * @param message * @param channel * @return */ @Override public Message<?> preSend(Message<?> message, MessageChannel channel) { System.out.println("preSend->"); return ChannelInterceptor.super.preSend(message, channel); } /** * 消息正在发送过程中被调用,主要用这个方法就行 * * @param message * @param channel * @param sent */ @Override public void postSend(Message<?> message, MessageChannel channel, boolean sent) { StompHeaderAccessor header = StompHeaderAccessor.wrap(message); System.out.println("postSend->" + header.getDestination()); } /** * 消息发送完成之后被调用,一般用来做资源释放等工作。 * * @param message * @param channel * @param sent * @param ex */ @Override public void afterSendCompletion(Message<?> message, MessageChannel channel, boolean sent, Exception ex) { System.out.println("afterSendCompletion->"); ChannelInterceptor.super.afterSendCompletion(message, channel, sent, ex); } } ``` **2. 配置类中添加拦截器** ```java @Configuration @EnableWebSocketMessageBroker public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { @Override public void configureClientInboundChannel(ChannelRegistration registration) { registration.interceptors(new SocketChannelInterceptor()); } @Override public void configureClientOutboundChannel(ChannelRegistration registration) { registration.interceptors(new SocketChannelInterceptor()); } } ``` <br/> # 2. 拦截器实现用户上线下线通知功能 ```java public class SocketChannelInterceptor implements ChannelInterceptor { @Override public void postSend(Message<?> message, MessageChannel channel, boolean sent) { StompHeaderAccessor header = StompHeaderAccessor.wrap(message); if (header.getCommand() == null) return; if (header.getCommand().equals(StompCommand.CONNECT)) { System.out.println("用户上线了"); } if ( header.getCommand().equals(StompCommand.DISCONNECT)) { System.out.println("用户下线了"); } } } ```