PreparedStatement должен быть подготовлен один раз в классе Singleton и снова использован. Как сделать это синглтоном? Мой код правильный? - PullRequest
0 голосов
/ 13 октября 2019

1. PreparedStatement создается при каждом вызове, и, следовательно, это влияет на производительность из-за нагрузки. Следовательно, мне нужно убедиться, что PreparedStatement должен быть подготовлен один раз в одноэлементном классе и снова использован повторно. Как этого добиться? Может ли кто-нибудь дать пример кода для этого, пожалуйста?

package com.cassandra.first;
import com.datastax.driver.core.Row;
import com.datastax.driver.core.PreparedStatement;
import org.stringtemplate.v4.compiler.STParser.singleElement_return;
import com.datastax.driver.core.BoundStatement;
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.utils.UUIDs;
import com.datastax.driver.core.Cluster.Builder;


public class App {
     public static PreparedStatement ps , ps1 ;


    public static void main( String[] args ) throws Exception
    {
        final String node = "localhost";
        final Integer port = 9042 ;

        CassandraConnector cc = new CassandraConnector();
        cc.connect(node, port);

        String cql = "SELECT * from test_01.sample_table_01;";
        try {
            ps = PreparedStatementCache.getInstance().getStatement(cc.getSession(), cql);
        } catch (Exception e) {
            e.printStackTrace();
        }

        BoundStatement boundStatement = ps.bind();

        ResultSet resultSet = cc.getSession().execute(boundStatement);

        for(Row row : resultSet) {
         System.out.format("%d  %s  %f\n" , row.getInt("RollNo"),row.getString("Name"),row.getDouble("Marks"));
        }

        System.out.println(ps);
        System.out.println("\nDone");

        String cql2 = "SELECT marks from test_01.sample_table_01;";
        try {
            ps1 = PreparedStatementCache.getInstance().getStatement(cc.getSession(), cql);
        } catch (NullPointerException e) {
            e.printStackTrace();
        }

        BoundStatement boundStatement2 = ps.bind();

        ResultSet resultSet2 = cc.getSession().execute(boundStatement2);
         for(Row row : resultSet2) {
             System.out.format("%d  %s  %f\n" , row.getInt("RollNo"),row.getString("Name"),row.getDouble("Marks"));
        }

        System.out.println(ps);
        System.out.println("\nDone"); 

        cc.close();

    }
}

Класс Singleton ->

package com.cassandra.first;

import com.datastax.driver.core.PreparedStatement;
import com.datastax.driver.core.Session;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


public class PreparedStatementCache {

    /* prevent cache incoherence issues*/
    private static volatile PreparedStatementCache cache;
    private static final Map<String, PreparedStatement> holder = new ConcurrentHashMap();
    int count = 1;

    private PreparedStatementCache() throws Exception {
        /*Prevent access through reflection api.*/
        if (cache != null) {
            System.out.println("- - "+ count + "- - ");
            count++;
            throw new Exception("Use getInstance() to retrieve the instance of this class");      
        }
    }


    /**
     * Double check locking pattern usage for singleton classes
     *
     * @return
     * @throws Exception 
     */
    public static PreparedStatementCache getInstance() throws Exception {
        if (cache == null) {                                                    //Check for the first time
            synchronized (PreparedStatementCache.class) {                       // second check in order to keep the operation atomic
                if (cache == null) {
                    cache = new PreparedStatementCache();
                }
            }
        }
        return cache;
    }


    /**
     * synchronize the caching bit.
     * @param session
     * @param cql
     * @return
     */
    public PreparedStatement getStatement(Session session, String cql) {
        PreparedStatement prepared_statement = holder.get(cql);

        if (prepared_statement == null) {
            synchronized (this) {
                prepared_statement = holder.get(cql);
                if (prepared_statement == null) {
                    prepared_statement = session.prepare(cql);
                    holder.put(cql, prepared_statement);
                }
            }
        }
        return prepared_statement;

      }


}
...