Springboot 통합 Netty 부팅에 주의가 필요합니다.

2827 단어 Netty

1. Netty 동기화 방식으로 Springboot 마스터 스레드 차단


일반적인 demo 수준의 netty 서버 코드 작성은 다음과 같습니다.
 try {
            serverBootstrap.group(bossGroup, workGroup)
                    .channel(NioServerSocketChannel.class)
                    //     
                    .childHandler(new NettyHandler())
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .childOption(ChannelOption.SO_KEEPALIVE, true);

            ChannelFuture future = serverBootstrap.bind(SERVER_PORT).sync();
            future.channel().closeFuture().sync();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //               
            workGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }

이 함수에서 다음 코드를 직접 호출하면 다음과 같습니다.
channelFuture.channel().closeFuture().sync();

Netty는 무한 순환에 들어가서 더 이상 불러오거나 스캔한 클래스를 불러오지 않습니다.mybatis,redis 등이 더 필요할 수도 있고 스캔이 안 될 수도 있어요.그래서 스레드 탱크execute를 사용해야 넷티가 Springboot을 막지 않게 할 수 있다. 
 

2. SpringBoot이 Netty를 통합할 때Handler 클래스에 null 주입


     
public class RequestHandler extends SimpleChannelInboundHandler {
    @Autowired
    private UserService userService;
    ....
}

서비스 주입 후null입니다. 자료를 찾았습니다. Springboot 비controller는 @Autowired 주석을null로 주입한 문제 (@Component 주석 추가, 초기화 함수 추가) 를 사용했지만 여전히 무효입니다.
위의 코드는 다음과 같이 업데이트되었습니다.
public class RequestHandler extends SimpleChannelInboundHandler {
    private static UserService userService;
    static {
        userService = SpringContextUtil.getBean(UserService.class);
    }
    ...
}

다음은 getBean의 도구 클래스입니다.
@Component
public class SpringContextUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if(SpringContextUtil.applicationContext == null) {
            SpringContextUtil.applicationContext = applicationContext;
        }
    }

    //  applicationContext
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    //  name   Bean.
    public static Object getBean(String name){
        return getApplicationContext().getBean(name);
    }

    //  class  Bean.
    public static  T getBean(Class clazz){
        return getApplicationContext().getBean(clazz);
    }

    //  name,  Clazz     Bean
    public static  T getBean(String name,Class clazz){
        return getApplicationContext().getBean(name, clazz);
    }

}

앞으로 넷티 개발 과정에서 겪은 문제점도 계속 업데이트할 예정이니 실제 과정에서의 문제점도 공유해 주시기 바랍니다.

좋은 웹페이지 즐겨찾기