All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.redislabs.picocliredis.RedisOptions Maven / Gradle / Ivy

There is a newer version: 2.0.2
Show newest version
package com.redislabs.picocliredis;

import java.time.Duration;
import java.util.List;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;

import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;

import com.redislabs.lettusearch.RediSearchClient;
import com.redislabs.lettusearch.StatefulRediSearchConnection;

import io.lettuce.core.AbstractRedisClient;
import io.lettuce.core.ClientOptions;
import io.lettuce.core.RedisClient;
import io.lettuce.core.RedisURI;
import io.lettuce.core.api.StatefulConnection;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.async.RedisAsyncCommands;
import io.lettuce.core.api.reactive.RedisReactiveCommands;
import io.lettuce.core.api.sync.BaseRedisCommands;
import io.lettuce.core.api.sync.RedisCommands;
import io.lettuce.core.cluster.ClusterClientOptions;
import io.lettuce.core.cluster.RedisClusterClient;
import io.lettuce.core.cluster.api.StatefulRedisClusterConnection;
import io.lettuce.core.cluster.api.async.RedisClusterAsyncCommands;
import io.lettuce.core.cluster.api.reactive.RedisClusterReactiveCommands;
import io.lettuce.core.cluster.api.sync.RedisClusterCommands;
import io.lettuce.core.pubsub.StatefulRedisPubSubConnection;
import io.lettuce.core.support.ConnectionPoolSupport;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import picocli.CommandLine.ArgGroup;
import picocli.CommandLine.Option;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisSentinelPool;
import redis.clients.jedis.util.Pool;

@Slf4j
public class RedisOptions {

	public static enum RedisDriver {
		Jedis, Lettuce
	}

	@Option(names = "--driver", description = "Redis driver: ${COMPLETION-CANDIDATES} (default: ${DEFAULT-VALUE})", paramLabel = "")
	private @Getter @Setter RedisDriver driver = RedisDriver.Lettuce;
	@Option(names = { "-s",
			"--servers" }, arity = "1..*", description = "Server endpoints (default: ${DEFAULT-VALUE})", paramLabel = "", hideParamSyntax = true)
	private List servers = new Servers(new Server());
	@Option(names = "--sentinel", description = "Sentinel master", paramLabel = "")
	private @Getter @Setter String sentinelMaster;
	@Option(names = "--auth", arity = "0..1", interactive = true, description = "Database login password", paramLabel = "")
	private @Getter @Setter String password;
	@Option(names = "--db", description = "Redis database number", paramLabel = "")
	private @Getter @Setter int database = 0;
	@Option(names = "--client", description = "Redis client name (default: ${DEFAULT-VALUE})", paramLabel = "")
	private @Getter @Setter String clientName = "picocli-redis";
	@Option(names = "--ssl", description = "SSL connection")
	private @Getter @Setter boolean ssl;
	@Option(names = "--cluster", description = "Connect to a Redis cluster")
	private @Getter @Setter boolean cluster;
	@Option(names = "--max-redirects", description = "Max cluster redirects (default: ${DEFAULT-VALUE})", paramLabel = "")
	private @Getter @Setter int maxRedirects = ClusterClientOptions.DEFAULT_MAX_REDIRECTS;
	@Option(names = "--max-total", description = "Max connections; -1 for no limit (default: ${DEFAULT-VALUE})", paramLabel = "")
	private @Getter @Setter int maxTotal = GenericObjectPoolConfig.DEFAULT_MAX_TOTAL;
	@Option(names = "--min-idle", description = "Min idle connections (default: ${DEFAULT-VALUE})", paramLabel = "")
	private @Getter @Setter int minIdle = GenericObjectPoolConfig.DEFAULT_MIN_IDLE;
	@Option(names = "--max-idle", description = "Max idle connections; -1 for no limit (default: ${DEFAULT-VALUE})", paramLabel = "")
	private @Getter @Setter int maxIdle = GenericObjectPoolConfig.DEFAULT_MAX_IDLE;
	@Option(names = "--max-wait", description = "Max duration; -1 for infinite (default: ${DEFAULT-VALUE})", paramLabel = "")
	private @Getter @Setter long maxWait = GenericObjectPoolConfig.DEFAULT_MAX_WAIT_MILLIS;
	@ArgGroup(exclusive = false, heading = "Jedis connection options%n", order = 2)
	private @Getter @Setter JedisOptions jedis = new JedisOptions();
	@ArgGroup(exclusive = false, heading = "Lettuce connection options%n", order = 3)
	private @Getter @Setter LettuceOptions lettuce = new LettuceOptions();

	public RedisOptions servers(Server... servers) {
		this.servers = new Servers(servers);
		return this;
	}

	public JedisCluster jedisCluster() {
		Set hostAndPort = servers.stream().map(s -> new HostAndPort(s.host(), s.port()))
				.collect(Collectors.toSet());
		if (password == null) {
			return new JedisCluster(hostAndPort, jedis.connectTimeout(), jedis.socketTimeout(), maxRedirects,
					configure(new JedisPoolConfig()));
		}
		return new JedisCluster(hostAndPort, jedis.connectTimeout(), jedis.socketTimeout(), maxRedirects, password,
				configure(new JedisPoolConfig()));
	}

	public Pool jedisPool() {
		JedisPoolConfig poolConfig = configure(new JedisPoolConfig());
		if (sentinelMaster == null) {
			String host = servers.get(0).host();
			int port = servers.get(0).port();
			log.debug("Creating Jedis connection pool for {}:{} with {}", host, port, poolConfig);
			return new JedisPool(poolConfig, host, port, jedis.connectTimeout(), jedis.socketTimeout(), password,
					database, clientName);
		}
		Set addresses = servers.stream().map(s -> s.address()).collect(Collectors.toSet());
		return new JedisSentinelPool(sentinelMaster, addresses, poolConfig, jedis.connectTimeout(),
				jedis.socketTimeout(), password, database, clientName);
	}

	@SuppressWarnings("rawtypes")
	private  T configure(T poolConfig) {
		poolConfig.setMaxTotal(maxTotal);
		poolConfig.setMaxIdle(maxIdle);
		poolConfig.setMinIdle(minIdle);
		poolConfig.setMaxWaitMillis(maxWait);
		poolConfig.setJmxEnabled(false);
		return poolConfig;
	}

	public > GenericObjectPool pool(Supplier supplier) {
		return ConnectionPoolSupport.createGenericObjectPool(supplier, configure(new GenericObjectPoolConfig<>()));
	}

	public AbstractRedisClient lettuceClient() {
		if (cluster) {
			return redisClusterClient();
		}
		return redisClient();
	}

	public RedisClient redisClient() {
		log.debug("Creating RedisClient");
		RedisClient client = RedisClient.create(lettuce.clientResources(), redisURI());
		client.setOptions(lettuce.clientOptions(ssl, ClientOptions.builder()));
		return client;
	}

	public RedisClusterClient redisClusterClient() {
		log.debug("Creating RedisClusterClient");
		List uris = servers.stream().map(s -> redisURI(s)).collect(Collectors.toList());
		RedisClusterClient client = RedisClusterClient.create(lettuce.clientResources(), uris);
		ClusterClientOptions.Builder builder = ClusterClientOptions.builder();
		builder.maxRedirects(maxRedirects);
		client.setOptions((ClusterClientOptions) lettuce.clientOptions(ssl, builder));
		return client;
	}

	public RediSearchClient rediSearchClient() {
		log.debug("Creating RediSearchClient");
		RediSearchClient client = RediSearchClient.create(lettuce.clientResources(), redisURI());
		client.setOptions(lettuce.clientOptions(ssl, ClientOptions.builder()));
		return client;
	}

	private RedisURI redisURI() {
		Server server = servers.get(0);
		if (sentinelMaster == null) {
			return redisURI(server);
		}
		RedisURI.Builder builder = RedisURI.Builder.sentinel(server.host(), server.port(), sentinelMaster);
		servers.forEach(s -> builder.withSentinel(s.host(), s.port()));
		return redisURI(builder);
	}

	private RedisURI redisURI(Server server) {
		RedisURI.Builder builder = RedisURI.Builder.redis(server.host()).withPort(server.port());
		return redisURI(builder);
	}

	private RedisURI redisURI(RedisURI.Builder builder) {
		builder.withClientName(clientName).withDatabase(database)
				.withTimeout(Duration.ofSeconds(lettuce.commandTimeout()));
		if (password != null) {
			builder.withPassword(password);
		}
		if (ssl) {
			builder.withSsl(ssl);
		}
		return builder.build();
	}

	public boolean isJedis() {
		return driver == RedisDriver.Jedis;
	}

	@SuppressWarnings("rawtypes")
	public Function lettuceApi() {
		if (cluster) {
			return lettuceClusterApi();
		}
		return lettuceStandaloneApi();
	}

	@SuppressWarnings("rawtypes")
	public Function lettuceAsyncApi() {
		if (cluster) {
			return lettuceClusterAsyncApi();
		}
		return lettuceStandaloneAsyncApi();
	}

	@SuppressWarnings("rawtypes")
	private Function lettuceStandaloneApi() {
		switch (lettuce.api()) {
		case Sync:
			return lettuceStandaloneSyncApi();
		case Reactive:
			return lettuceStandaloneReactiveApi();
		default:
			return lettuceStandaloneAsyncApi();
		}
	}

	private Function, RedisCommands> lettuceStandaloneSyncApi() {
		return (Function, RedisCommands>) StatefulRedisConnection::sync;
	}

	private Function, RedisReactiveCommands> lettuceStandaloneReactiveApi() {
		return (Function, RedisReactiveCommands>) StatefulRedisConnection::reactive;
	}

	private Function, RedisAsyncCommands> lettuceStandaloneAsyncApi() {
		return (Function, RedisAsyncCommands>) StatefulRedisConnection::async;
	}

	@SuppressWarnings("rawtypes")
	private Function lettuceClusterApi() {
		switch (lettuce.api()) {
		case Sync:
			return lettuceClusterSyncApi();
		case Reactive:
			return lettuceClusterReactiveApi();
		default:
			return lettuceClusterAsyncApi();
		}
	}

	private Function, RedisClusterAsyncCommands> lettuceClusterAsyncApi() {
		return (Function, RedisClusterAsyncCommands>) StatefulRedisClusterConnection::async;
	}

	private Function, RedisClusterReactiveCommands> lettuceClusterReactiveApi() {
		return (Function, RedisClusterReactiveCommands>) StatefulRedisClusterConnection::reactive;
	}

	private Function, RedisClusterCommands> lettuceClusterSyncApi() {
		return (Function, RedisClusterCommands>) StatefulRedisClusterConnection::sync;
	}

	public Function, ?> lettuSearchApi() {
		switch (lettuce.api()) {
		case Sync:
			return StatefulRediSearchConnection::sync;
		case Reactive:
			return StatefulRediSearchConnection::reactive;
		default:
			return StatefulRediSearchConnection::async;
		}
	}

	public BaseRedisCommands redisCommands() {
		if (cluster) {
			return redisClusterClient().connect().sync();
		}
		return redisClient().connect().sync();
	}

	public StatefulConnection statefulConnection() {
		if (cluster) {
			return redisClusterClient().connect();
		}
		return redisClient().connect();
	}

	public GenericObjectPool> lettucePool() {
		if (cluster) {
			return pool(redisClusterClient()::connect);
		}
		return pool(redisClient()::connect);
	}

	public StatefulRedisPubSubConnection statefulRedisPubSubConnection() {
		if (cluster) {
			return redisClusterClient().connectPubSub();
		}
		return redisClient().connectPubSub();
	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy