jiazx0107
2025-09-01 ce4f9b9f72a4269a1f25812dadd59bfb92c7b3cf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package com.ld.io.netty;
 
import com.ld.io.api.IoMsgConsumer;
import com.ld.io.api.IoSession;
 
import io.netty.util.concurrent.DefaultThreadFactory;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
import java.util.concurrent.*;
 
/**
 * 线程池 处理接收到的信息, 不占用netty的工作线程
 */
class ReceiveMessageThreadPool {
    private static final String POOL_NAME = "netty-receive-message";
    private final Logger logger = LoggerFactory.getLogger(getClass());
    private static ExecutorService executorService;
    private IoMsgConsumer messageConsumer;
 
    public ReceiveMessageThreadPool(IoMsgConsumer messageConsumer) {
        this.messageConsumer = messageConsumer;
    }
 
    static {
        ThreadFactory threadFactory = new DefaultThreadFactory(POOL_NAME);
        executorService = new ThreadPoolExecutor(100, 100, 0L,
                TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(500),
                threadFactory, new ThreadPoolExecutor.DiscardOldestPolicy());
    }
 
    void execute(IoSession session, byte[] bytes) {
        executorService
                .submit(() -> {
                    if (messageConsumer != null) {
                        String msg;
                        try {
                            //msg = new String(bytes, "UTF-8");
                            //logger.info("临时打印查看报文:"+ msg);
                            messageConsumer.consume(session, bytes);
                        } catch (Exception e) {
                            try {
                                msg = new String(bytes, "UTF-8");
                            } catch (Exception e1) {
                                msg = "转换为字符串异常";
                            }
                            logger.error(
                                    "Consume message happened error, business key="
                                            + session.getBusinessKey()
                                            + ", msg=" + msg, e);
                        }
                    } else {
                        logger.error("Message consumer not config! All request was ignored!");
                    }
                });
    }
}