package com.zy.core.netty; 
 | 
  
 | 
import com.core.common.SnowflakeIdWorker; 
 | 
import com.zy.core.netty.cache.ChannelAttrKey; 
 | 
import com.zy.core.netty.handle.PackageServerHandler; 
 | 
import com.zy.core.netty.handle.ProtectorHandler; 
 | 
import com.zy.core.netty.handle.ProtocolDecoder; 
 | 
import com.zy.core.netty.handle.ProtocolEncoder; 
 | 
import com.zy.core.netty.properties.TcpProperties; 
 | 
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 SnowflakeIdWorker snowflakeIdWorker; 
 | 
    @Autowired 
 | 
    private TcpProperties tcpProperties; 
 | 
    @Autowired 
 | 
    private ProtocolEncoder protocolEncoder; 
 | 
    @Autowired 
 | 
    private PackageServerHandler packageServerHandler; 
 | 
    @Autowired 
 | 
    private ProtectorHandler protectorHandler; 
 | 
  
 | 
    /** 
 | 
     * Set some channel handlers on channel pipeline 
 | 
     */ 
 | 
    @Override 
 | 
    protected void initChannel(Channel channel) { 
 | 
        channel.pipeline() 
 | 
                // 心跳 
 | 
                .addLast(new IdleStateHandler(tcpProperties.getHeartSeconds(), 0, 0)) 
 | 
                // 编码器 
 | 
                .addLast(protocolEncoder) 
 | 
                // 解码器 
 | 
                .addLast(new ProtocolDecoder(snowflakeIdWorker)) 
 | 
                // 校验码处理器 
 | 
//                .addLast(validateHandler) 
 | 
                // 认证处理器 
 | 
//                .addLast(vehAuthHandler) 
 | 
                // 业务处理器 
 | 
                .addLast(packageServerHandler) 
 | 
                // 通道保护器 
 | 
                .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); 
 | 
    } 
 | 
  
 | 
} 
 |