Merge branch 'main' into main

This commit is contained in:
zongzibinbin
2023-07-06 21:02:20 +08:00
committed by GitHub
16 changed files with 139 additions and 139 deletions

View File

@@ -13,7 +13,7 @@ import lombok.Getter;
public enum CommonErrorEnum implements ErrorEnum { public enum CommonErrorEnum implements ErrorEnum {
SYSTEM_ERROR(-1, "系统出小差了,请稍后再试哦~~"), SYSTEM_ERROR(-1, "系统出小差了,请稍后再试哦~~"),
PARAM_VALID(-2, "参数校验失败"), PARAM_VALID(-2, "参数校验失败{0}"),
FREQUENCY_LIMIT(-3, "请求太频繁了,请稍后再试哦~~"), FREQUENCY_LIMIT(-3, "请求太频繁了,请稍后再试哦~~"),
LOCK_LIMIT(-4, "请求太频繁了,请稍后再试哦~~"), LOCK_LIMIT(-4, "请求太频繁了,请稍后再试哦~~"),
; ;

View File

@@ -6,7 +6,6 @@ import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT; import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier; import com.auth0.jwt.interfaces.JWTVerifier;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test; import org.junit.Test;
import java.util.Date; import java.util.Date;
@@ -18,27 +17,18 @@ public class CreateTokenTest {
@Test @Test
public void create(){ public void create(){
String token = JWT.create() String token = JWT.create()
.withClaim("uid", 123L) // 只存一个uid信息其他的自己去redis查 .withClaim("uid", 10004L) // 只存一个uid信息其他的自己去redis查
.withClaim("createTime", new Date()) .withClaim("createTime", new Date())
.sign(Algorithm.HMAC256("dsfsdfsdfsdfsd")); // signature .sign(Algorithm.HMAC256("dsfsdfsdfsdfsd")); // signature
log.info("生成的token为 {}",token); log.info("生成的token为 {}",token);
try { try {
JWTVerifier verifier = JWT.require(Algorithm.HMAC256("dsfsdfsdfsdfsd")).build(); JWTVerifier verifier = JWT.require(Algorithm.HMAC256("dsfsdfsdfsdfsc")).build();
DecodedJWT jwt = verifier.verify(token); DecodedJWT jwt = verifier.verify(token);
log.info(jwt.getClaims().toString()); log.info(jwt.getClaims().toString());
} catch (Exception e) { } catch (Exception e) {
log.info("decode error,token:{}", token, e); log.info("decode error,token:{}", token, e);
} }
} }
@Test
public void verifyToken(){
String token = JWT.create()
.withClaim("uid", 1) // 只存一个uid信息其他的自己去redis查
.withClaim("createTime", new Date())
.sign(Algorithm.HMAC256("dsfsdfsdfsdfsd")); // signature
log.info("生成的token为{}",token);
}
} }

View File

@@ -94,7 +94,6 @@ public class ChatController {
private void filterBlackMsg(CursorPageBaseResp<ChatMessageResp> memberPage) { private void filterBlackMsg(CursorPageBaseResp<ChatMessageResp> memberPage) {
Set<String> blackMembers = getBlackUidSet(); Set<String> blackMembers = getBlackUidSet();
memberPage.getList().removeIf(a -> blackMembers.contains(a.getFromUser().getUid().toString())); memberPage.getList().removeIf(a -> blackMembers.contains(a.getFromUser().getUid().toString()));
System.out.println(1);
} }
@PostMapping("/msg") @PostMapping("/msg")

View File

@@ -29,13 +29,21 @@ public abstract class AbstractChatAIHandler {
protected UserService userService; protected UserService userService;
@PostConstruct @PostConstruct
private void init() { protected void init() {
ChatAIHandlerFactory.register(getChatAIUserId(), getChatAIName(), this); if (isUse()) {
ChatAIHandlerFactory.register(getChatAIUserId(), this);
}
} }
/**
* 是否启用
*
* @return boolean
*/
protected abstract boolean isUse();
// 获取机器人id // 获取机器人id
public abstract Long getChatAIUserId(); public abstract Long getChatAIUserId();
// 获取机器人名称
public abstract String getChatAIName();
public void chat(Message message) { public void chat(Message message) {
if (!supports(message)) { if (!supports(message)) {
@@ -44,7 +52,7 @@ public abstract class AbstractChatAIHandler {
threadPoolTaskExecutor.execute(() -> { threadPoolTaskExecutor.execute(() -> {
String text = doChat(message); String text = doChat(message);
if (StringUtils.isNotBlank(text)) { if (StringUtils.isNotBlank(text)) {
answerMsg(text, message.getRoomId(), message.getFromUid()); answerMsg(text, message);
} }
}); });
} }
@@ -66,30 +74,34 @@ public abstract class AbstractChatAIHandler {
protected abstract String doChat(Message message); protected abstract String doChat(Message message);
protected void answerMsg(String text, Long roomId, Long uid) { protected void answerMsg(String text, Message replyMessage) {
UserInfoResp userInfo = userService.getUserInfo(uid); UserInfoResp userInfo = userService.getUserInfo(replyMessage.getFromUid());
text = "@" + userInfo.getName() + " " + text; text = "@" + userInfo.getName() + " " + text;
if (text.length() < 450) { if (text.length() < 800) {
save(text, roomId, uid); save(text, replyMessage);
}else { } else {
int maxLen = 450; int maxLen = 800;
int len = text.length(); int len = text.length();
int count = (len + maxLen - 1) / maxLen; int count = (len + maxLen - 1) / maxLen;
for (int i = 0; i < count; i++) { for (int i = 0; i < count; i++) {
int start = i * maxLen; int start = i * maxLen;
int end = Math.min(start + maxLen, len); int end = Math.min(start + maxLen, len);
save(text.substring(start, end), roomId, uid); save(text.substring(start, end), replyMessage);
} }
} }
} }
private void save(String text, Long roomId, Long uid) { private void save(String text, Message replyMessage) {
Long roomId = replyMessage.getRoomId();
Long uid = replyMessage.getFromUid();
Long id = replyMessage.getId();
ChatMessageReq answerReq = new ChatMessageReq(); ChatMessageReq answerReq = new ChatMessageReq();
answerReq.setRoomId(roomId); answerReq.setRoomId(roomId);
answerReq.setMsgType(MessageTypeEnum.TEXT.getType()); answerReq.setMsgType(MessageTypeEnum.TEXT.getType());
TextMsgReq textMsgReq = new TextMsgReq(); TextMsgReq textMsgReq = new TextMsgReq();
textMsgReq.setContent(text); textMsgReq.setContent(text);
textMsgReq.setReplyMsgId(replyMessage.getId());
textMsgReq.setAtUidList(Collections.singletonList(uid)); textMsgReq.setAtUidList(Collections.singletonList(uid));
answerReq.setBody(textMsgReq); answerReq.setBody(textMsgReq);
chatService.sendMsg(answerReq, getChatAIUserId()); chatService.sendMsg(answerReq, getChatAIUserId());

View File

@@ -1,7 +1,6 @@
package com.abin.mallchat.custom.chatai.handler; package com.abin.mallchat.custom.chatai.handler;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils; import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@@ -9,11 +8,9 @@ import java.util.concurrent.ConcurrentHashMap;
public class ChatAIHandlerFactory { public class ChatAIHandlerFactory {
private static final Map<Long, AbstractChatAIHandler> CHATAI_ID_MAP = new ConcurrentHashMap<>(); private static final Map<Long, AbstractChatAIHandler> CHATAI_ID_MAP = new ConcurrentHashMap<>();
private static final Map<String, AbstractChatAIHandler> CHATAI_NAME_MAP = new ConcurrentHashMap<>();
public static void register(Long aIUserId, String name, AbstractChatAIHandler chatAIHandler) { public static void register(Long aIUserId, AbstractChatAIHandler chatAIHandler) {
CHATAI_ID_MAP.put(aIUserId, chatAIHandler); CHATAI_ID_MAP.put(aIUserId, chatAIHandler);
CHATAI_NAME_MAP.put(name, chatAIHandler);
} }
public static AbstractChatAIHandler getChatAIHandlerById(List<Long> userIds) { public static AbstractChatAIHandler getChatAIHandlerById(List<Long> userIds) {
@@ -28,15 +25,4 @@ public class ChatAIHandlerFactory {
} }
return null; return null;
} }
public static AbstractChatAIHandler getChatAIHandlerByName(String text) {
if (StringUtils.isBlank(text)) {
return null;
}
for (Map.Entry<String, AbstractChatAIHandler> entry : CHATAI_NAME_MAP.entrySet()) {
if (text.contains("@"+entry.getKey())) {
return entry.getValue();
}
}
return null;
}
} }

View File

@@ -7,6 +7,7 @@ import com.abin.mallchat.common.common.constant.RedisKey;
import com.abin.mallchat.common.common.utils.RedisUtils; import com.abin.mallchat.common.common.utils.RedisUtils;
import com.abin.mallchat.custom.chatai.properties.ChatGLM2Properties; import com.abin.mallchat.custom.chatai.properties.ChatGLM2Properties;
import com.abin.mallchat.custom.chatai.utils.ChatGLM2Utils; import com.abin.mallchat.custom.chatai.utils.ChatGLM2Utils;
import com.abin.mallchat.custom.user.domain.vo.response.user.UserInfoResp;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@@ -36,27 +37,42 @@ public class ChatGLM2Handler extends AbstractChatAIHandler {
private static final Random RANDOM = new Random(); private static final Random RANDOM = new Random();
private static String AI_NAME;
@Autowired @Autowired
private ChatGLM2Properties glm2Properties; private ChatGLM2Properties glm2Properties;
@Override
protected void init() {
super.init();
if (isUse()) {
UserInfoResp userInfo = userService.getUserInfo(glm2Properties.getAIUserId());
if (userInfo == null) {
log.error("根据AIUserId:{} 找不到用户信息", glm2Properties.getAIUserId());
throw new RuntimeException("根据AIUserId找不到用户信息");
}
if (StringUtils.isBlank(userInfo.getName())) {
log.warn("根据AIUserId:{} 找到的用户信息没有name", glm2Properties.getAIUserId());
throw new RuntimeException("根据AIUserId: " + glm2Properties.getAIUserId() + " 找到的用户没有名字");
}
AI_NAME = userInfo.getName();
}
}
@Override
protected boolean isUse() {
return glm2Properties.isUse();
}
@Override @Override
public Long getChatAIUserId() { public Long getChatAIUserId() {
return glm2Properties.getAIUserId(); return glm2Properties.getAIUserId();
} }
@Override
public String getChatAIName() {
if (StringUtils.isNotBlank(glm2Properties.getAIUserName())) {
return glm2Properties.getAIUserName();
}
String name = userService.getUserInfo(glm2Properties.getAIUserId()).getName();
glm2Properties.setAIUserName(name);
return name;
}
@Override @Override
protected String doChat(Message message) { protected String doChat(Message message) {
String content = message.getContent().replace("@" +glm2Properties.getAIUserName(), "").trim(); String content = message.getContent().replace("@" + AI_NAME, "").trim();
Long uid = message.getFromUid(); Long uid = message.getFromUid();
Long minute; Long minute;
String text; String text;
@@ -73,7 +89,7 @@ public class ChatGLM2Handler extends AbstractChatAIHandler {
.send(); .send();
text = ChatGLM2Utils.parseText(response); text = ChatGLM2Utils.parseText(response);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); log.warn("glm2 doChat warn:", e);
return getErrorText(); return getErrorText();
} }
if (StringUtils.isNotBlank(text)) { if (StringUtils.isNotBlank(text)) {
@@ -132,7 +148,7 @@ public class ChatGLM2Handler extends AbstractChatAIHandler {
if (StringUtils.isBlank(message.getContent())) { if (StringUtils.isBlank(message.getContent())) {
return false; return false;
} }
return StringUtils.contains(message.getContent(), "@" + glm2Properties.getAIUserName()) return StringUtils.contains(message.getContent(), "@" + AI_NAME)
&& StringUtils.isNotBlank(message.getContent().replace(glm2Properties.getAIUserName(), "").trim()); && StringUtils.isNotBlank(message.getContent().replace(AI_NAME, "").trim());
} }
} }

View File

@@ -2,41 +2,59 @@ package com.abin.mallchat.custom.chatai.handler;
import cn.hutool.http.HttpResponse; import cn.hutool.http.HttpResponse;
import com.abin.mallchat.common.chat.domain.entity.Message; import com.abin.mallchat.common.chat.domain.entity.Message;
import com.abin.mallchat.common.chat.domain.entity.msg.MessageExtra;
import com.abin.mallchat.common.common.constant.RedisKey; import com.abin.mallchat.common.common.constant.RedisKey;
import com.abin.mallchat.common.common.utils.DateUtils; import com.abin.mallchat.common.common.utils.DateUtils;
import com.abin.mallchat.common.common.utils.RedisUtils; import com.abin.mallchat.common.common.utils.RedisUtils;
import com.abin.mallchat.custom.chatai.properties.ChatGPTProperties; import com.abin.mallchat.custom.chatai.properties.ChatGPTProperties;
import com.abin.mallchat.custom.chatai.utils.ChatGPTUtils; import com.abin.mallchat.custom.chatai.utils.ChatGPTUtils;
import com.abin.mallchat.custom.user.domain.vo.response.user.UserInfoResp;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
@Slf4j
@Component @Component
public class GPTChatAIHandler extends AbstractChatAIHandler { public class GPTChatAIHandler extends AbstractChatAIHandler {
@Autowired @Autowired
private ChatGPTProperties chatGPTProperties; private ChatGPTProperties chatGPTProperties;
private static String AI_NAME;
@Override
protected void init() {
super.init();
UserInfoResp userInfo = userService.getUserInfo(chatGPTProperties.getAIUserId());
if (userInfo == null) {
log.error("根据AIUserId:{} 找不到用户信息", chatGPTProperties.getAIUserId());
throw new RuntimeException("根据AIUserId: " + chatGPTProperties.getAIUserId() + " 找不到用户信息");
}
if (StringUtils.isBlank(userInfo.getName())) {
log.warn("根据AIUserId:{} 找到的用户信息没有name", chatGPTProperties.getAIUserId());
throw new RuntimeException("根据AIUserId: " + chatGPTProperties.getAIUserId() + " 找到的用户没有名字");
}
AI_NAME = userInfo.getName();
}
@Override
protected boolean isUse() {
return chatGPTProperties.isUse();
}
@Override @Override
public Long getChatAIUserId() { public Long getChatAIUserId() {
return chatGPTProperties.getAIUserId(); return chatGPTProperties.getAIUserId();
} }
@Override
public String getChatAIName() {
if (StringUtils.isNotBlank(chatGPTProperties.getAIUserName())) {
return chatGPTProperties.getAIUserName();
}
String name = userService.getUserInfo(chatGPTProperties.getAIUserId()).getName();
chatGPTProperties.setAIUserName(name);
return name;
}
@Override @Override
protected String doChat(Message message) { protected String doChat(Message message) {
String content = message.getContent().replace("@" + chatGPTProperties.getAIUserName(), "").trim(); String content = message.getContent().replace("@" + AI_NAME, "").trim();
Long uid = message.getFromUid(); Long uid = message.getFromUid();
Long chatNum; Long chatNum;
String text; String text;
@@ -48,12 +66,13 @@ public class GPTChatAIHandler extends AbstractChatAIHandler {
response = ChatGPTUtils.create(chatGPTProperties.getKey()) response = ChatGPTUtils.create(chatGPTProperties.getKey())
.proxyUrl(chatGPTProperties.getProxyUrl()) .proxyUrl(chatGPTProperties.getProxyUrl())
.model(chatGPTProperties.getModelName()) .model(chatGPTProperties.getModelName())
.timeout(chatGPTProperties.getTimeout())
.prompt(content) .prompt(content)
.send(); .send();
text = ChatGPTUtils.parseText(response); text = ChatGPTUtils.parseText(response);
userChatNumInrc(uid); userChatNumInrc(uid);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); log.warn("gpt doChat warn:", e);
text = "我累了,明天再聊吧"; text = "我累了,明天再聊吧";
} }
} }
@@ -78,21 +97,21 @@ public class GPTChatAIHandler extends AbstractChatAIHandler {
} }
/* 前端传@信息后取消注释 */ /* 前端传@信息后取消注释 */
// MessageExtra extra = message.getExtra(); MessageExtra extra = message.getExtra();
// if (extra == null) { if (extra == null) {
// return false; return false;
// } }
// if (CollectionUtils.isEmpty(extra.getAtUidList())) { if (CollectionUtils.isEmpty(extra.getAtUidList())) {
// return false; return false;
// } }
// if (!extra.getAtUidList().contains(chatGPTProperties.getAIUserId())) { if (!extra.getAtUidList().contains(chatGPTProperties.getAIUserId())) {
// return false; return false;
// } }
if (StringUtils.isBlank(message.getContent())) { if (StringUtils.isBlank(message.getContent())) {
return false; return false;
} }
return StringUtils.contains(message.getContent(), "@" + chatGPTProperties.getAIUserName()) return StringUtils.contains(message.getContent(), "@" + AI_NAME)
&& StringUtils.isNotBlank(message.getContent().replace(chatGPTProperties.getAIUserName(), "").trim()); && StringUtils.isNotBlank(message.getContent().replace(AI_NAME, "").trim());
} }
} }

View File

@@ -30,11 +30,6 @@ public class ChatGLM2Properties {
*/ */
private Long AIUserId; private Long AIUserId;
/**
* 机器人名称
*/
private String AIUserName;
/** /**
* 每个用户每?分钟可以请求一次 * 每个用户每?分钟可以请求一次
*/ */

View File

@@ -18,11 +18,6 @@ public class ChatGPTProperties {
* 机器人 id * 机器人 id
*/ */
private Long AIUserId; private Long AIUserId;
/**
* 机器人名称
*/
private String AIUserName;
/** /**
* 模型名称 * 模型名称
*/ */
@@ -36,6 +31,11 @@ public class ChatGPTProperties {
*/ */
private String proxyUrl; private String proxyUrl;
/**
* 超时
*/
private Integer timeout = 60*1000;
/** /**
* 用户每天条数限制 * 用户每天条数限制
*/ */

View File

@@ -45,6 +45,11 @@ public class TokenInterceptor implements HandlerInterceptor {
return true; return true;
} }
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
MDC.remove(MDCKey.UID);
}
/** /**
* 判断是不是公共方法,可以未登录访问的 * 判断是不是公共方法,可以未登录访问的
* *

View File

@@ -33,8 +33,10 @@ import org.springframework.context.ApplicationEventPublisher;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import java.time.Duration; import java.time.Duration;
import java.util.*; import java.util.*;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;

View File

@@ -1,5 +1,6 @@
package com.abin.mallchat.custom.user.websocket; package com.abin.mallchat.custom.user.websocket;
import cn.hutool.core.net.url.UrlBuilder;
import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.FullHttpRequest;
@@ -13,7 +14,16 @@ public class HttpHeadersHandler extends ChannelInboundHandlerAdapter {
@Override @Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof FullHttpRequest) { if (msg instanceof FullHttpRequest) {
HttpHeaders headers = ((FullHttpRequest) msg).headers(); FullHttpRequest request = (FullHttpRequest) msg;
UrlBuilder urlBuilder = UrlBuilder.ofHttp(request.uri());
// 获取token参数
String token = urlBuilder.getQuery().get("token").toString();
NettyUtil.setAttr(ctx.channel(), NettyUtil.TOKEN, token);
// 获取请求路径
request.setUri(urlBuilder.getPath().toString());
HttpHeaders headers = request.headers();
String ip = headers.get("X-Real-IP"); String ip = headers.get("X-Real-IP");
if (StringUtils.isEmpty(ip)) {//如果没经过nginx就直接获取远端地址 if (StringUtils.isEmpty(ip)) {//如果没经过nginx就直接获取远端地址
InetSocketAddress address = (InetSocketAddress) ctx.channel().remoteAddress(); InetSocketAddress address = (InetSocketAddress) ctx.channel().remoteAddress();
@@ -21,7 +31,10 @@ public class HttpHeadersHandler extends ChannelInboundHandlerAdapter {
} }
NettyUtil.setAttr(ctx.channel(), NettyUtil.IP, ip); NettyUtil.setAttr(ctx.channel(), NettyUtil.IP, ip);
ctx.pipeline().remove(this); ctx.pipeline().remove(this);
ctx.fireChannelRead(request);
}else
{
ctx.fireChannelRead(msg);
} }
ctx.fireChannelRead(msg);
} }
} }

View File

@@ -1,6 +1,7 @@
package com.abin.mallchat.custom.user.websocket; package com.abin.mallchat.custom.user.websocket;
import io.netty.channel.Channel; import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.WebSocketServerHandshaker;
import io.netty.util.Attribute; import io.netty.util.Attribute;
import io.netty.util.AttributeKey; import io.netty.util.AttributeKey;
@@ -15,6 +16,7 @@ public class NettyUtil {
public static AttributeKey<String> TOKEN = AttributeKey.valueOf("token"); public static AttributeKey<String> TOKEN = AttributeKey.valueOf("token");
public static AttributeKey<String> IP = AttributeKey.valueOf("ip"); public static AttributeKey<String> IP = AttributeKey.valueOf("ip");
public static AttributeKey<Long> UID = AttributeKey.valueOf("uid"); public static AttributeKey<Long> UID = AttributeKey.valueOf("uid");
public static AttributeKey<WebSocketServerHandshaker> HANDSHAKER_ATTR_KEY = AttributeKey.valueOf(WebSocketServerHandshaker.class, "HANDSHAKER");
public static <T> void setAttr(Channel channel, AttributeKey<T> attributeKey, T data) { public static <T> void setAttr(Channel channel, AttributeKey<T> attributeKey, T data) {
Attribute<T> attr = channel.attr(attributeKey); Attribute<T> attr = channel.attr(attributeKey);

View File

@@ -10,6 +10,7 @@ import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec; import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.logging.LogLevel; import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler; import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler; import io.netty.handler.stream.ChunkedWriteHandler;
@@ -88,7 +89,7 @@ public class NettyWebSocketServer {
* 4. WebSocketServerProtocolHandler 核心功能是把 http协议升级为 ws 协议,保持长连接; * 4. WebSocketServerProtocolHandler 核心功能是把 http协议升级为 ws 协议,保持长连接;
* 是通过一个状态码 101 来切换的 * 是通过一个状态码 101 来切换的
*/ */
pipeline.addLast(new WebSocketHandshakeHandler()); pipeline.addLast(new WebSocketServerProtocolHandler("/"));
// 自定义handler ,处理业务逻辑 // 自定义handler ,处理业务逻辑
pipeline.addLast(new NettyWebSocketServerHandler()); pipeline.addLast(new NettyWebSocketServerHandler());
} }

View File

@@ -19,10 +19,12 @@ import lombok.extern.slf4j.Slf4j;
@Slf4j @Slf4j
public class NettyWebSocketServerHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> { public class NettyWebSocketServerHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
private WebSocketService webSocketService;
// 当web客户端连接后触发该方法 // 当web客户端连接后触发该方法
@Override @Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception { public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
// getService().connect(ctx.channel()); this.webSocketService = getService();
} }
// 客户端离线 // 客户端离线
@@ -45,7 +47,7 @@ public class NettyWebSocketServerHandler extends SimpleChannelInboundHandler<Tex
} }
private void userOffLine(ChannelHandlerContext ctx) { private void userOffLine(ChannelHandlerContext ctx) {
getService().removed(ctx.channel()); this.webSocketService.removed(ctx.channel());
ctx.channel().close(); ctx.channel().close();
} }
@@ -66,10 +68,10 @@ public class NettyWebSocketServerHandler extends SimpleChannelInboundHandler<Tex
userOffLine(ctx); userOffLine(ctx);
} }
} else if (evt == WebSocketServerProtocolHandler.ServerHandshakeStateEvent.HANDSHAKE_COMPLETE) { } else if (evt == WebSocketServerProtocolHandler.ServerHandshakeStateEvent.HANDSHAKE_COMPLETE) {
getService().connect(ctx.channel()); this.webSocketService.connect(ctx.channel());
String token = NettyUtil.getAttr(ctx.channel(), NettyUtil.TOKEN); String token = NettyUtil.getAttr(ctx.channel(), NettyUtil.TOKEN);
if (StrUtil.isNotBlank(token)) { if (StrUtil.isNotBlank(token)) {
getService().authorize(ctx.channel(), new WSAuthorize(token)); this.webSocketService.authorize(ctx.channel(), new WSAuthorize(token));
} }
} }
super.userEventTriggered(ctx, evt); super.userEventTriggered(ctx, evt);
@@ -93,13 +95,13 @@ public class NettyWebSocketServerHandler extends SimpleChannelInboundHandler<Tex
WSReqTypeEnum wsReqTypeEnum = WSReqTypeEnum.of(wsBaseReq.getType()); WSReqTypeEnum wsReqTypeEnum = WSReqTypeEnum.of(wsBaseReq.getType());
switch (wsReqTypeEnum) { switch (wsReqTypeEnum) {
case LOGIN: case LOGIN:
getService().handleLoginReq(ctx.channel()); this.webSocketService.handleLoginReq(ctx.channel());
log.info("请求二维码 = " + msg.text()); log.info("请求二维码 = " + msg.text());
break; break;
case HEARTBEAT: case HEARTBEAT:
break; break;
case AUTHORIZE: case AUTHORIZE:
getService().authorize(ctx.channel(), JSONUtil.toBean(wsBaseReq.getData(), WSAuthorize.class)); this.webSocketService.authorize(ctx.channel(), JSONUtil.toBean(wsBaseReq.getData(), WSAuthorize.class));
log.info("主动认证 = " + msg.text()); log.info("主动认证 = " + msg.text());
break; break;
default: default:

View File

@@ -1,42 +0,0 @@
package com.abin.mallchat.custom.user.websocket;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.websocketx.WebSocketServerHandshaker;
import io.netty.handler.codec.http.websocketx.WebSocketServerHandshakerFactory;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
public class WebSocketHandshakeHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof FullHttpRequest) {
FullHttpRequest request = (FullHttpRequest) msg;
String token = request.headers().get("Sec-Websocket-Protocol");
NettyUtil.setAttr(ctx.channel(), NettyUtil.TOKEN, token);
// 构建WebSocket握手处理器
WebSocketServerHandshakerFactory handshakeFactory = new WebSocketServerHandshakerFactory(
request.uri(), token, false);
WebSocketServerHandshaker handshake = handshakeFactory.newHandshaker(request);
final ChannelFuture handshakeFuture = handshake.handshake(ctx.channel(), request);
ctx.pipeline().remove(this);
handshakeFuture.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) {
if (!future.isSuccess()) {
ctx.fireExceptionCaught(future.cause());
} else {
// 手动触发WebSocket握手状态事件
ctx.fireUserEventTriggered(
WebSocketServerProtocolHandler.ServerHandshakeStateEvent.HANDSHAKE_COMPLETE);
}
}
});
} else {
super.channelRead(ctx, msg);
}
}
}