Search in sources :

Example 1 with Tuple3

use of org.fisco.bcos.web3j.tuples.generated.Tuple3 in project web3sdk by FISCO-BCOS.

the class PerfomanceTableQuery method main.

public static void main(String[] args) throws Exception {
    try {
        String groupId = args[3];
        ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
        Service service = context.getBean(Service.class);
        service.setGroupId(Integer.parseInt(groupId));
        service.run();
        System.out.println("Start test...");
        System.out.println("===================================================================");
        ChannelEthereumService channelEthereumService = new ChannelEthereumService();
        channelEthereumService.setChannelService(service);
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(500);
        Web3j web3 = Web3j.build(channelEthereumService, 15 * 100, scheduledExecutorService, Integer.parseInt(groupId));
        Credentials credentials = Credentials.create("b83261efa42895c38c6c2364ca878f43e77f3cddbc922bf57d0d48070f79feb6");
        BigInteger gasPrice = new BigInteger("30000000");
        BigInteger gasLimit = new BigInteger("30000000");
        String command = args[0];
        Integer count = 0;
        Integer qps = 0;
        switch(command) {
            case "trans":
                count = Integer.parseInt(args[1]);
                qps = Integer.parseInt(args[2]);
                break;
            default:
                System.out.println("Args: <trans> <Total> <QPS>");
        }
        ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor();
        threadPool.setCorePoolSize(200);
        threadPool.setMaxPoolSize(500);
        threadPool.setQueueCapacity(count);
        threadPool.initialize();
        System.out.println("Deploying contract...");
        TableTest tabletest = TableTest.deploy(web3, credentials, gasPrice, gasLimit).send();
        PerfomanceCollector collector = new PerfomanceCollector();
        collector.setTotal(count);
        RateLimiter limiter = RateLimiter.create(qps);
        Integer area = count / 10;
        final Integer total = count;
        Random random = new Random(System.currentTimeMillis());
        System.out.println("Start test,total:" + count);
        for (Integer i = 0; i < count; ++i) {
            threadPool.execute(new Runnable() {

                @Override
                public void run() {
                    limiter.acquire();
                    PerfomanceTableTestCallback callback = new PerfomanceTableTestCallback();
                    callback.setCollector(collector);
                    try {
                        Long time_before = System.currentTimeMillis();
                        long _id = getNextID();
                        Random r = new Random();
                        long l1 = r.nextLong();
                        Tuple3<List<byte[]>, List<BigInteger>, List<byte[]>> lists = tabletest.select("fruit" + l1 % TableTestClient.modevalue).send();
                        Long time_after = System.currentTimeMillis();
                        TransactionReceipt receipt = new TransactionReceipt();
                        receipt.setStatus("0");
                        collector.onSelectMessage(receipt, time_after - time_before);
                    /*
                                    List<byte[]> value1 = lists.getValue1();
                                          List<BigInteger> value2 = lists.getValue2();
                                          List<byte[]> value3 = lists.getValue3();
                                          logger.info("record numbers = " + value1.size());
                                          System.out.println("record numbers = " + value1.size());
                                          for (int i = 0; i < value1.size(); i++) {
                                            String name = new String(value1.get(i));
                                            logger.info("name = " + name);
                                            System.out.println("name = " + name);
                                            int item_id = value2.get(i).intValue();
                                            logger.info("item_id = " + item_id);
                                            System.out.println("item_id = " + item_id);
                                            String item_name = new String(value3.get(i));
                                            logger.info("item_name = " + item_name);
                                            System.out.println("item_name = " + item_name);
                                          }

                                          */
                    } catch (Exception e) {
                        TransactionReceipt receipt = new TransactionReceipt();
                        receipt.setStatus("-1");
                        callback.onResponse(receipt);
                        logger.error("Error sending:", e);
                    }
                    int current = sended.incrementAndGet();
                    if (current >= area && ((current % area) == 0)) {
                        System.out.println("Already sended: " + current + "/" + total + " transactions");
                    }
                }
            });
        }
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(-1);
    }
}
Also used : ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) TransactionReceipt(org.fisco.bcos.web3j.protocol.core.methods.response.TransactionReceipt) ChannelEthereumService(org.fisco.bcos.web3j.protocol.channel.ChannelEthereumService) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) Service(org.fisco.bcos.channel.client.Service) ChannelEthereumService(org.fisco.bcos.web3j.protocol.channel.ChannelEthereumService) RateLimiter(com.google.common.util.concurrent.RateLimiter) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) BigInteger(java.math.BigInteger) ApplicationContext(org.springframework.context.ApplicationContext) ClassPathXmlApplicationContext(org.springframework.context.support.ClassPathXmlApplicationContext) Web3j(org.fisco.bcos.web3j.protocol.Web3j) Random(java.util.Random) ClassPathXmlApplicationContext(org.springframework.context.support.ClassPathXmlApplicationContext) Tuple3(org.fisco.bcos.web3j.tuples.generated.Tuple3) AtomicLong(java.util.concurrent.atomic.AtomicLong) BigInteger(java.math.BigInteger) ThreadPoolTaskExecutor(org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor) Credentials(org.fisco.bcos.web3j.crypto.Credentials)

Example 2 with Tuple3

use of org.fisco.bcos.web3j.tuples.generated.Tuple3 in project web3sdk by FISCO-BCOS.

the class ChannelConnections method startConnect.

public void startConnect() throws Exception {
    if (running) {
        logger.debug("running");
        return;
    }
    logger.debug(" start connect. ");
    // init netty
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    bootstrap.group(workerGroup);
    bootstrap.channel(NioSocketChannel.class);
    bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
    // set connect timeout
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, (int) connectTimeout);
    final ChannelConnections selfService = this;
    final ThreadPoolTaskExecutor selfThreadPool = threadPool;
    SslContext sslContext = (EncryptType.encryptType == EncryptType.ECDSA_TYPE) ? initSslContext() : initSMSslContext();
    SslContext finalSslContext = sslContext;
    bootstrap.handler(new ChannelInitializer<SocketChannel>() {

        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            /*
                         * Each connection is fetched from the socketChannel, using the new
                         * handler connection information
                         */
            ChannelHandler handler = new ChannelHandler();
            handler.setConnections(selfService);
            handler.setThreadPool(selfThreadPool);
            SslHandler sslHandler = finalSslContext.newHandler(ch.alloc());
            /**
             * set ssl handshake timeout
             */
            sslHandler.setHandshakeTimeoutMillis(sslHandShakeTimeout);
            ch.pipeline().addLast(sslHandler, new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, -4, 0), new IdleStateHandler(idleTimeout, idleTimeout, idleTimeout, TimeUnit.MILLISECONDS), handler);
        }
    });
    List<Tuple3<String, Integer, ChannelFuture>> tuple3List = new ArrayList<>();
    // try to connect to all nodes
    for (ConnectionInfo connectionInfo : connections) {
        String IP = connectionInfo.getHost();
        Integer port = connectionInfo.getPort();
        ChannelFuture channelFuture = bootstrap.connect(IP, port);
        tuple3List.add(new Tuple3<>(IP, port, channelFuture));
    }
    boolean atLeastOneConnectSuccess = false;
    List<String> errorMessageList = new ArrayList<>();
    // Wait for all connection operations to complete
    for (Tuple3<String, Integer, ChannelFuture> tuple3 : tuple3List) {
        ChannelFuture connectFuture = tuple3.getValue3().awaitUninterruptibly();
        if (!connectFuture.isSuccess()) {
            logger.error(" connect to {}:{}, error: {}", tuple3.getValue1(), tuple3.getValue2(), connectFuture.cause().getMessage());
            String connectFailedMessage = Objects.isNull(connectFuture.cause()) ? "connect to " + tuple3.getValue1() + ":" + tuple3.getValue2() + " failed" : connectFuture.cause().getMessage();
            errorMessageList.add(connectFailedMessage);
        } else {
            // tcp connect success and waiting for SSL handshake
            logger.trace(" connect to {}:{} success", tuple3.getValue1(), tuple3.getValue2());
            SslHandler sslhandler = connectFuture.channel().pipeline().get(SslHandler.class);
            if (Objects.isNull(sslhandler)) {
                String sslHandshakeFailedMessage = " ssl handshake failed:/" + tuple3.getValue1() + ":" + tuple3.getValue2();
                logger.debug(" SslHandler is null, host: {}, port: {}", tuple3.getValue1(), tuple3.getValue2());
                errorMessageList.add(sslHandshakeFailedMessage);
                continue;
            }
            Future<Channel> sshHandshakeFuture = sslhandler.handshakeFuture().awaitUninterruptibly();
            if (sshHandshakeFuture.isSuccess()) {
                atLeastOneConnectSuccess = true;
                logger.trace(" ssl handshake success {}:{}", tuple3.getValue1(), tuple3.getValue2());
            } else {
                String sslHandshakeFailedMessage = " ssl handshake failed:/" + tuple3.getValue1() + ":" + tuple3.getValue2();
                errorMessageList.add(sslHandshakeFailedMessage);
            }
        }
    }
    // All connections failed
    if (!atLeastOneConnectSuccess) {
        logger.error(" all connections have failed, " + errorMessageList.toString());
        throw new RuntimeException(" Failed to connect to nodes: " + errorMessageList.toString() + helpInfo);
    }
    running = true;
    logger.debug(" start connect end. ");
}
Also used : SocketChannel(io.netty.channel.socket.SocketChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) ArrayList(java.util.ArrayList) LengthFieldBasedFrameDecoder(io.netty.handler.codec.LengthFieldBasedFrameDecoder) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) SslContext(io.netty.handler.ssl.SslContext) ChannelFuture(io.netty.channel.ChannelFuture) SocketChannel(io.netty.channel.socket.SocketChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Channel(io.netty.channel.Channel) SSLException(javax.net.ssl.SSLException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) NoSuchProviderException(java.security.NoSuchProviderException) SslHandler(io.netty.handler.ssl.SslHandler) BigInteger(java.math.BigInteger) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) EventLoopGroup(io.netty.channel.EventLoopGroup) IdleStateHandler(io.netty.handler.timeout.IdleStateHandler) Tuple3(org.fisco.bcos.web3j.tuples.generated.Tuple3) ThreadPoolTaskExecutor(org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor)

Aggregations

BigInteger (java.math.BigInteger)2 Tuple3 (org.fisco.bcos.web3j.tuples.generated.Tuple3)2 ThreadPoolTaskExecutor (org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor)2 RateLimiter (com.google.common.util.concurrent.RateLimiter)1 Channel (io.netty.channel.Channel)1 ChannelFuture (io.netty.channel.ChannelFuture)1 EventLoopGroup (io.netty.channel.EventLoopGroup)1 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)1 SocketChannel (io.netty.channel.socket.SocketChannel)1 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)1 LengthFieldBasedFrameDecoder (io.netty.handler.codec.LengthFieldBasedFrameDecoder)1 SslContext (io.netty.handler.ssl.SslContext)1 SslHandler (io.netty.handler.ssl.SslHandler)1 IdleStateHandler (io.netty.handler.timeout.IdleStateHandler)1 IOException (java.io.IOException)1 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)1 NoSuchProviderException (java.security.NoSuchProviderException)1 CertificateException (java.security.cert.CertificateException)1 InvalidKeySpecException (java.security.spec.InvalidKeySpecException)1 ArrayList (java.util.ArrayList)1