Search in sources :

Example 51 with Singleton

use of javax.inject.Singleton in project presto by prestodb.

the class CassandraClientModule method createCassandraSession.

@Singleton
@Provides
public static CassandraSession createCassandraSession(CassandraConnectorId connectorId, CassandraClientConfig config, JsonCodec<List<ExtraColumnMetadata>> extraColumnMetadataCodec) {
    requireNonNull(config, "config is null");
    requireNonNull(extraColumnMetadataCodec, "extraColumnMetadataCodec is null");
    Cluster.Builder clusterBuilder = Cluster.builder().withProtocolVersion(config.getProtocolVersion());
    List<String> contactPoints = requireNonNull(config.getContactPoints(), "contactPoints is null");
    checkArgument(!contactPoints.isEmpty(), "empty contactPoints");
    clusterBuilder.withPort(config.getNativeProtocolPort());
    clusterBuilder.withReconnectionPolicy(new ExponentialReconnectionPolicy(500, 10000));
    clusterBuilder.withRetryPolicy(config.getRetryPolicy().getPolicy());
    LoadBalancingPolicy loadPolicy = new RoundRobinPolicy();
    if (config.isUseDCAware()) {
        requireNonNull(config.getDcAwareLocalDC(), "DCAwarePolicy localDC is null");
        DCAwareRoundRobinPolicy.Builder builder = DCAwareRoundRobinPolicy.builder().withLocalDc(config.getDcAwareLocalDC());
        if (config.getDcAwareUsedHostsPerRemoteDc() > 0) {
            builder.withUsedHostsPerRemoteDc(config.getDcAwareUsedHostsPerRemoteDc());
            if (config.isDcAwareAllowRemoteDCsForLocal()) {
                builder.allowRemoteDCsForLocalConsistencyLevel();
            }
        }
        loadPolicy = builder.build();
    }
    if (config.isUseTokenAware()) {
        loadPolicy = new TokenAwarePolicy(loadPolicy, config.isTokenAwareShuffleReplicas());
    }
    if (config.isUseWhiteList()) {
        checkArgument(!config.getWhiteListAddresses().isEmpty(), "empty WhiteListAddresses");
        List<InetSocketAddress> whiteList = new ArrayList<>();
        for (String point : config.getWhiteListAddresses()) {
            whiteList.add(new InetSocketAddress(point, config.getNativeProtocolPort()));
        }
        loadPolicy = new WhiteListPolicy(loadPolicy, whiteList);
    }
    clusterBuilder.withLoadBalancingPolicy(loadPolicy);
    SocketOptions socketOptions = new SocketOptions();
    socketOptions.setReadTimeoutMillis(toIntExact(config.getClientReadTimeout().toMillis()));
    socketOptions.setConnectTimeoutMillis(toIntExact(config.getClientConnectTimeout().toMillis()));
    if (config.getClientSoLinger() != null) {
        socketOptions.setSoLinger(config.getClientSoLinger());
    }
    if (config.isTlsEnabled()) {
        SslContextProvider sslContextProvider = new SslContextProvider(config.getKeystorePath(), config.getKeystorePassword(), config.getTruststorePath(), config.getTruststorePassword());
        sslContextProvider.buildSslContext().ifPresent(context -> clusterBuilder.withSSL(JdkSSLOptions.builder().withSSLContext(context).build()));
    }
    clusterBuilder.withSocketOptions(socketOptions);
    if (config.getUsername() != null && config.getPassword() != null) {
        clusterBuilder.withCredentials(config.getUsername(), config.getPassword());
    }
    QueryOptions options = new QueryOptions();
    options.setFetchSize(config.getFetchSize());
    options.setConsistencyLevel(config.getConsistencyLevel());
    clusterBuilder.withQueryOptions(options);
    if (config.getSpeculativeExecutionLimit() > 1) {
        clusterBuilder.withSpeculativeExecutionPolicy(new ConstantSpeculativeExecutionPolicy(// delay before a new execution is launched
        config.getSpeculativeExecutionDelay().toMillis(), // maximum number of executions
        config.getSpeculativeExecutionLimit()));
    }
    return new NativeCassandraSession(connectorId.toString(), extraColumnMetadataCodec, new ReopeningCluster(() -> {
        contactPoints.forEach(clusterBuilder::addContactPoint);
        return clusterBuilder.build();
    }), config.getNoHostAvailableRetryTimeout());
}
Also used : InetSocketAddress(java.net.InetSocketAddress) SocketOptions(com.datastax.driver.core.SocketOptions) ArrayList(java.util.ArrayList) Cluster(com.datastax.driver.core.Cluster) QueryOptions(com.datastax.driver.core.QueryOptions) ConstantSpeculativeExecutionPolicy(com.datastax.driver.core.policies.ConstantSpeculativeExecutionPolicy) LoadBalancingPolicy(com.datastax.driver.core.policies.LoadBalancingPolicy) DCAwareRoundRobinPolicy(com.datastax.driver.core.policies.DCAwareRoundRobinPolicy) WhiteListPolicy(com.datastax.driver.core.policies.WhiteListPolicy) SslContextProvider(com.facebook.presto.cassandra.util.SslContextProvider) ExponentialReconnectionPolicy(com.datastax.driver.core.policies.ExponentialReconnectionPolicy) TokenAwarePolicy(com.datastax.driver.core.policies.TokenAwarePolicy) RoundRobinPolicy(com.datastax.driver.core.policies.RoundRobinPolicy) DCAwareRoundRobinPolicy(com.datastax.driver.core.policies.DCAwareRoundRobinPolicy) Singleton(javax.inject.Singleton) Provides(com.google.inject.Provides)

Example 52 with Singleton

use of javax.inject.Singleton in project presto by prestodb.

the class KuduModule method createKuduClientSession.

@Singleton
@Provides
KuduClientSession createKuduClientSession(KuduConnectorId connectorId, KuduClientConfig config) {
    requireNonNull(config, "config is null");
    KuduClient client;
    if (!config.isKerberosAuthEnabled()) {
        client = KuduUtil.createKuduClient(config);
    } else {
        KuduUtil.initKerberosENV(config.getKerberosPrincipal(), config.getKerberosKeytab(), config.isKerberosAuthDebugEnabled());
        client = KuduUtil.createKuduKerberosClient(config);
    }
    SchemaEmulation strategy;
    if (config.isSchemaEmulationEnabled()) {
        strategy = new SchemaEmulationByTableNameConvention(config.getSchemaEmulationPrefix());
    } else {
        strategy = new NoSchemaEmulation();
    }
    return new KuduClientSession(connectorId, client, strategy, config.isKerberosAuthEnabled());
}
Also used : SchemaEmulationByTableNameConvention(com.facebook.presto.kudu.schema.SchemaEmulationByTableNameConvention) SchemaEmulation(com.facebook.presto.kudu.schema.SchemaEmulation) NoSchemaEmulation(com.facebook.presto.kudu.schema.NoSchemaEmulation) NoSchemaEmulation(com.facebook.presto.kudu.schema.NoSchemaEmulation) KuduClient(org.apache.kudu.client.KuduClient) Singleton(javax.inject.Singleton) Provides(com.google.inject.Provides)

Example 53 with Singleton

use of javax.inject.Singleton in project GeekNews by codeestX.

the class HttpModule method provideClient.

@Singleton
@Provides
OkHttpClient provideClient(OkHttpClient.Builder builder) {
    if (BuildConfig.DEBUG) {
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);
        builder.addInterceptor(loggingInterceptor);
    }
    File cacheFile = new File(Constants.PATH_CACHE);
    Cache cache = new Cache(cacheFile, 1024 * 1024 * 50);
    Interceptor cacheInterceptor = new Interceptor() {

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            if (!SystemUtil.isNetworkConnected()) {
                request = request.newBuilder().cacheControl(CacheControl.FORCE_CACHE).build();
            }
            Response response = chain.proceed(request);
            if (SystemUtil.isNetworkConnected()) {
                int maxAge = 0;
                // 有网络时, 不缓存, 最大保存时长为0
                response.newBuilder().header("Cache-Control", "public, max-age=" + maxAge).removeHeader("Pragma").build();
            } else {
                // 无网络时,设置超时为4周
                int maxStale = 60 * 60 * 24 * 28;
                response.newBuilder().header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale).removeHeader("Pragma").build();
            }
            return response;
        }
    };
    // Interceptor apikey = new Interceptor() {
    // @Override
    // public Response intercept(Chain chain) throws IOException {
    // Request request = chain.request();
    // request = request.newBuilder()
    // .addHeader("apikey",Constants.KEY_API)
    // .build();
    // return chain.proceed(request);
    // }
    // }
    // 设置统一的请求头部参数
    // builder.addInterceptor(apikey);
    // 设置缓存
    builder.addNetworkInterceptor(cacheInterceptor);
    builder.addInterceptor(cacheInterceptor);
    builder.cache(cache);
    // 设置超时
    builder.connectTimeout(10, TimeUnit.SECONDS);
    builder.readTimeout(20, TimeUnit.SECONDS);
    builder.writeTimeout(20, TimeUnit.SECONDS);
    // 错误重连
    builder.retryOnConnectionFailure(true);
    return builder.build();
}
Also used : Response(okhttp3.Response) Request(okhttp3.Request) File(java.io.File) Interceptor(okhttp3.Interceptor) HttpLoggingInterceptor(okhttp3.logging.HttpLoggingInterceptor) HttpLoggingInterceptor(okhttp3.logging.HttpLoggingInterceptor) Cache(okhttp3.Cache) Singleton(javax.inject.Singleton) Provides(dagger.Provides)

Example 54 with Singleton

use of javax.inject.Singleton in project redisson by redisson.

the class RedissonClientProducer method create.

@Produces
@Singleton
@DefaultBean
public RedissonClient create() throws IOException {
    InputStream configStream;
    Optional<String> configFile = ConfigProvider.getConfig().getOptionalValue("quarkus.redisson.file", String.class);
    if (configFile.isPresent()) {
        configStream = getClass().getResourceAsStream(configFile.get());
    } else {
        configStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("redisson.yaml");
    }
    String config;
    if (configStream != null) {
        byte[] array = new byte[configStream.available()];
        configStream.read(array);
        config = new String(array, StandardCharsets.UTF_8);
    } else {
        String yaml = PropertiesConvertor.toYaml("quarkus.redisson.", ConfigProvider.getConfig().getPropertyNames(), prop -> {
            return ConfigProvider.getConfig().getValue(prop, String.class);
        });
        config = yaml;
    }
    ConfigSupport support = new ConfigSupport() {

        {
            yamlMapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
        }
    };
    Config c = support.fromYAML(config, Config.class);
    redisson = Redisson.create(c);
    return redisson;
}
Also used : ConfigSupport(org.redisson.config.ConfigSupport) InputStream(java.io.InputStream) Config(org.redisson.config.Config) DefaultBean(io.quarkus.arc.DefaultBean) Produces(javax.enterprise.inject.Produces) Singleton(javax.inject.Singleton)

Example 55 with Singleton

use of javax.inject.Singleton in project Just-Another-Android-App by athkalia.

the class BuildTypeAwareModule method providesNetworkBehavior.

@Provides
@Singleton
@SuppressWarnings("checkstyle:magicnumber")
public static NetworkBehavior providesNetworkBehavior() {
    NetworkBehavior networkBehavior = NetworkBehavior.create();
    networkBehavior.setDelay(1, TimeUnit.SECONDS);
    // Delay can vary by 50%.
    networkBehavior.setVariancePercent(50);
    // 20% of all calls are failing.
    networkBehavior.setFailurePercent(20);
    return networkBehavior;
}
Also used : NetworkBehavior(retrofit2.mock.NetworkBehavior) Singleton(javax.inject.Singleton) Provides(dagger.Provides)

Aggregations

Singleton (javax.inject.Singleton)168 Provides (dagger.Provides)98 Provides (com.google.inject.Provides)57 HttpLoggingInterceptor (okhttp3.logging.HttpLoggingInterceptor)21 Named (javax.inject.Named)17 OkHttpClient (okhttp3.OkHttpClient)17 Cache (okhttp3.Cache)10 List (java.util.List)9 ConfigBinder.configBinder (com.facebook.airlift.configuration.ConfigBinder.configBinder)8 Binder (com.google.inject.Binder)8 Module (com.google.inject.Module)8 CachingStripeMetadataSource (com.facebook.presto.orc.CachingStripeMetadataSource)7 DwrfAwareStripeMetadataSourceFactory (com.facebook.presto.orc.DwrfAwareStripeMetadataSourceFactory)7 OrcDataSourceId (com.facebook.presto.orc.OrcDataSourceId)7 StorageStripeMetadataSource (com.facebook.presto.orc.StorageStripeMetadataSource)7 StripeMetadataSource (com.facebook.presto.orc.StripeMetadataSource)7 StripeMetadataSourceFactory (com.facebook.presto.orc.StripeMetadataSourceFactory)7 CachingOrcFileTailSource (com.facebook.presto.orc.cache.CachingOrcFileTailSource)7 OrcCacheConfig (com.facebook.presto.orc.cache.OrcCacheConfig)7 OrcFileTailSource (com.facebook.presto.orc.cache.OrcFileTailSource)7