#
vincentlu
2025-05-13 ebd2f4397a92c6a5096de1b86d59154363344720
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package com.zy.acs.gateway;
 
import com.zy.acs.gateway.cache.ChannelAttrKey;
import com.zy.acs.gateway.config.SystemProperties;
import com.zy.acs.gateway.handler.*;
import com.zy.acs.gateway.handler.coder.ProtocolDecoder;
import com.zy.acs.gateway.handler.coder.ProtocolEncoder;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.Attribute;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
 
import java.util.HashMap;
import java.util.Map;
 
 
/**
 * handler管道
 * 控制所有netty handler流向
 * 待完成: 动态管理handler
 * Created by vincent on 2019-04-02
 */
@Component
@ChannelHandler.Sharable
public class HandlerInitializer extends ChannelInitializer<Channel> {
 
    @Autowired
    private SystemProperties systemProperties;
    @Autowired
    private ProtocolEncoder protocolEncoder;
    @Autowired
    private ValidateHandler validateHandler;
    @Autowired
    private MessageBodyHandler messageBodyHandler;
    @Autowired
    private AgvAuthHandler agvAuthHandler;
    @Autowired
    private AgvPackageServerHandler agvPackageServerHandler;
    @Autowired
    private ProtectorHandler protectorHandler;
 
    /**
     * Set some channel handlers on channel pipeline
     */
    @Override
    protected void initChannel(Channel channel) {
        channel.pipeline()
                // 心跳
                .addLast(new IdleStateHandler(systemProperties.getHeartSeconds(), 0, 0))
                // 编码器
                .addLast(protocolEncoder)
                // 解码器
                .addLast(new ProtocolDecoder(4096))
                // 校验码处理器
                .addLast(validateHandler)
                // 报文分解处理器
                .addLast(messageBodyHandler)
                // 认证处理器
                .addLast(agvAuthHandler)
                // 业务处理器
                .addLast(agvPackageServerHandler)
                // 通道保护器
                .addLast(protectorHandler)
        ;
 
        // Channel局部变量,相当于线程的ThreadLocal
//        initAttrTrack(channel);
    }
 
    /**
     *  Init channel attr track
     */
    private void initAttrTrack(Channel channel){
        Attribute<Map<String, Object>> coolTrackAttr = channel.attr(ChannelAttrKey.DATA_MAP_ATTR);
        Map<String, Object> trackMap = new HashMap<>();
        coolTrackAttr.setIfAbsent(trackMap);
    }
 
}