netty EventExecutorGroup线程重复执行

时间:2017-11-15 08:57:48

标签: multithreading netty

最近,我使用netty构建服务器程序,但我遇到了一个难题, 有时当我的程序收到连接时,它将使用多个线程来处理相同的连接。

例如,当客户端连接到服务器时,客户端提供服务器端数据A,然后会有多个不同的线程接收数据A并对其进行处理,这使得我的数据库经常插入相同的数据

我该如何解决这个问题?

我的代码:

private int port;
private Conf MyConf;
public static String Path;

public ChiconyServerBootstrap(String Path)
{

    try
    {
        MyConf = new Conf(Path);
        port = MyConf.getPort();
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
}

public void start()
{
    ServerBootstrap serverbootstrap = new ServerBootstrap();
    NioEventLoopGroup connect_group = new NioEventLoopGroup();
    NioEventLoopGroup io_group = new NioEventLoopGroup();
    final EventExecutorGroup work_group = new DefaultEventExecutorGroup(10);

    try
    {
        serverbootstrap.group(connect_group, io_group);
        serverbootstrap.channel(NioServerSocketChannel.class);
        serverbootstrap.childHandler(new ChannelInitializer<SocketChannel>()
        {
            @Override
            public void initChannel(SocketChannel ch) throws Exception
            {
                ch.pipeline().addLast(new ByteArrayDecoder());
                ch.pipeline().addLast(work_group, new WorkHandler());
            }
        });

        serverbootstrap.childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, 60);
        serverbootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
        ChannelFuture future = serverbootstrap.bind(new InetSocketAddress(port)).sync();
        future.channel().closeFuture().sync();
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
    finally
    {
        connect_group.shutdownGracefully();
        io_group.shutdownGracefully();
        work_group.shutdownGracefully();
    }
}

public static void main(String[] args)
{
    ChiconyServerBootstrap server;  
    Path = "./Conf/config.properties";
    server = new ChiconyServerBootstrap(Path);
    server.start();
}

NioEventLoopGroup中的WorkHandler:

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception
{       
    //Initialization parameter
}

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception
{
    //Accept the parameters from the client
}

@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception
{       
    //Perform business logic, data insert into database
}

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) 
{   

}

0 个答案:

没有答案