|
@@ -1,15 +1,10 @@
|
|
|
package cn.reghao.oss.store.util;
|
|
package cn.reghao.oss.store.util;
|
|
|
|
|
|
|
|
-import cn.reghao.oss.api.dto.WebBody;
|
|
|
|
|
-import com.fasterxml.jackson.databind.ObjectMapper;
|
|
|
|
|
-import io.netty.buffer.ByteBuf;
|
|
|
|
|
-import io.netty.buffer.ByteBufOutputStream;
|
|
|
|
|
import io.netty.buffer.Unpooled;
|
|
import io.netty.buffer.Unpooled;
|
|
|
import io.netty.channel.ChannelHandlerContext;
|
|
import io.netty.channel.ChannelHandlerContext;
|
|
|
import io.netty.handler.codec.http.*;
|
|
import io.netty.handler.codec.http.*;
|
|
|
import lombok.extern.slf4j.Slf4j;
|
|
import lombok.extern.slf4j.Slf4j;
|
|
|
|
|
|
|
|
-import java.io.OutputStream;
|
|
|
|
|
import java.nio.charset.StandardCharsets;
|
|
import java.nio.charset.StandardCharsets;
|
|
|
|
|
|
|
|
/**
|
|
/**
|
|
@@ -18,29 +13,6 @@ import java.nio.charset.StandardCharsets;
|
|
|
*/
|
|
*/
|
|
|
@Slf4j
|
|
@Slf4j
|
|
|
public class ResponseHelper {
|
|
public class ResponseHelper {
|
|
|
- private static final ObjectMapper mapper = new ObjectMapper();
|
|
|
|
|
-
|
|
|
|
|
- public static void sendJsonResponse(ChannelHandlerContext ctx, HttpResponseStatus status, WebBody webBody) {
|
|
|
|
|
- // 1. 申请池化 ByteBuf
|
|
|
|
|
- ByteBuf content = ctx.alloc().buffer();
|
|
|
|
|
- try {
|
|
|
|
|
- // 2. 利用 ByteBufOutputStream 减少中间 String 拷贝
|
|
|
|
|
- try (ByteBufOutputStream os = new ByteBufOutputStream(content)) {
|
|
|
|
|
- mapper.writeValue((OutputStream)os, webBody);
|
|
|
|
|
- }
|
|
|
|
|
-
|
|
|
|
|
- FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, content);
|
|
|
|
|
- response.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json; charset=UTF-8");
|
|
|
|
|
- // 明确指定 Content-Length,否则某些客户端会一直等待 Body 结束
|
|
|
|
|
- response.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());
|
|
|
|
|
- ctx.writeAndFlush(response);
|
|
|
|
|
-
|
|
|
|
|
- } catch (Exception e) {
|
|
|
|
|
- content.release(); // 异常时手动释放
|
|
|
|
|
- log.error("JSON 序列化失败", e);
|
|
|
|
|
- }
|
|
|
|
|
- }
|
|
|
|
|
-
|
|
|
|
|
public static void sendJsonResponse(ChannelHandlerContext ctx, String jsonBody) {
|
|
public static void sendJsonResponse(ChannelHandlerContext ctx, String jsonBody) {
|
|
|
FullHttpResponse response = new DefaultFullHttpResponse(
|
|
FullHttpResponse response = new DefaultFullHttpResponse(
|
|
|
HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
|
|
HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
|