Search in sources :

Example 1 with JedisPool

use of redis.clients.jedis.JedisPool in project qi4j-sdk by Qi4j.

the class RedisMapEntityStoreMixin method activateService.

@Override
public void activateService() throws Exception {
    configuration.refresh();
    RedisEntityStoreConfiguration config = configuration.get();
    String host = config.host().get() == null ? DEFAULT_HOST : config.host().get();
    int port = config.port().get() == null ? Protocol.DEFAULT_PORT : config.port().get();
    int timeout = config.timeout().get() == null ? Protocol.DEFAULT_TIMEOUT : config.timeout().get();
    String password = config.password().get();
    int database = config.database().get() == null ? Protocol.DEFAULT_DATABASE : config.database().get();
    pool = new JedisPool(new JedisPoolConfig(), host, port, timeout, password, database);
}
Also used : JedisPool(redis.clients.jedis.JedisPool) JedisPoolConfig(redis.clients.jedis.JedisPoolConfig)

Example 2 with JedisPool

use of redis.clients.jedis.JedisPool in project dubbo by alibaba.

the class RedisRegistry method doRegister.

@Override
public void doRegister(URL url) {
    String key = toCategoryPath(url);
    String value = url.toFullString();
    String expire = String.valueOf(System.currentTimeMillis() + expirePeriod);
    boolean success = false;
    RpcException exception = null;
    for (Map.Entry<String, JedisPool> entry : jedisPools.entrySet()) {
        JedisPool jedisPool = entry.getValue();
        try {
            Jedis jedis = jedisPool.getResource();
            try {
                jedis.hset(key, value, expire);
                jedis.publish(key, Constants.REGISTER);
                success = true;
                if (!replicate) {
                    //  如果服务器端已同步数据,只需写入单台机器
                    break;
                }
            } finally {
                jedisPool.returnResource(jedis);
            }
        } catch (Throwable t) {
            exception = new RpcException("Failed to register service to redis registry. registry: " + entry.getKey() + ", service: " + url + ", cause: " + t.getMessage(), t);
        }
    }
    if (exception != null) {
        if (success) {
            logger.warn(exception.getMessage(), exception);
        } else {
            throw exception;
        }
    }
}
Also used : Jedis(redis.clients.jedis.Jedis) RpcException(com.alibaba.dubbo.rpc.RpcException) JedisPool(redis.clients.jedis.JedisPool) HashMap(java.util.HashMap) ConcurrentMap(java.util.concurrent.ConcurrentMap) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap)

Example 3 with JedisPool

use of redis.clients.jedis.JedisPool in project dubbo by alibaba.

the class RedisRegistry method doSubscribe.

@Override
public void doSubscribe(final URL url, final NotifyListener listener) {
    String service = toServicePath(url);
    Notifier notifier = notifiers.get(service);
    if (notifier == null) {
        Notifier newNotifier = new Notifier(service);
        notifiers.putIfAbsent(service, newNotifier);
        notifier = notifiers.get(service);
        if (notifier == newNotifier) {
            notifier.start();
        }
    }
    boolean success = false;
    RpcException exception = null;
    for (Map.Entry<String, JedisPool> entry : jedisPools.entrySet()) {
        JedisPool jedisPool = entry.getValue();
        try {
            Jedis jedis = jedisPool.getResource();
            try {
                if (service.endsWith(Constants.ANY_VALUE)) {
                    admin = true;
                    Set<String> keys = jedis.keys(service);
                    if (keys != null && keys.size() > 0) {
                        Map<String, Set<String>> serviceKeys = new HashMap<String, Set<String>>();
                        for (String key : keys) {
                            String serviceKey = toServicePath(key);
                            Set<String> sk = serviceKeys.get(serviceKey);
                            if (sk == null) {
                                sk = new HashSet<String>();
                                serviceKeys.put(serviceKey, sk);
                            }
                            sk.add(key);
                        }
                        for (Set<String> sk : serviceKeys.values()) {
                            doNotify(jedis, sk, url, Arrays.asList(listener));
                        }
                    }
                } else {
                    doNotify(jedis, jedis.keys(service + Constants.PATH_SEPARATOR + Constants.ANY_VALUE), url, Arrays.asList(listener));
                }
                success = true;
                // 只需读一个服务器的数据
                break;
            } finally {
                jedisPool.returnResource(jedis);
            }
        } catch (Throwable t) {
            // 尝试下一个服务器
            exception = new RpcException("Failed to subscribe service from redis registry. registry: " + entry.getKey() + ", service: " + url + ", cause: " + t.getMessage(), t);
        }
    }
    if (exception != null) {
        if (success) {
            logger.warn(exception.getMessage(), exception);
        } else {
            throw exception;
        }
    }
}
Also used : HashSet(java.util.HashSet) Set(java.util.Set) HashMap(java.util.HashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Jedis(redis.clients.jedis.Jedis) RpcException(com.alibaba.dubbo.rpc.RpcException) JedisPool(redis.clients.jedis.JedisPool) HashMap(java.util.HashMap) ConcurrentMap(java.util.concurrent.ConcurrentMap) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap)

Example 4 with JedisPool

use of redis.clients.jedis.JedisPool in project dubbo by alibaba.

the class RedisProtocol method refer.

public <T> Invoker<T> refer(final Class<T> type, final URL url) throws RpcException {
    try {
        GenericObjectPool.Config config = new GenericObjectPool.Config();
        config.testOnBorrow = url.getParameter("test.on.borrow", true);
        config.testOnReturn = url.getParameter("test.on.return", false);
        config.testWhileIdle = url.getParameter("test.while.idle", false);
        if (url.getParameter("max.idle", 0) > 0)
            config.maxIdle = url.getParameter("max.idle", 0);
        if (url.getParameter("min.idle", 0) > 0)
            config.minIdle = url.getParameter("min.idle", 0);
        if (url.getParameter("max.active", 0) > 0)
            config.maxActive = url.getParameter("max.active", 0);
        if (url.getParameter("max.wait", 0) > 0)
            config.maxWait = url.getParameter("max.wait", 0);
        if (url.getParameter("num.tests.per.eviction.run", 0) > 0)
            config.numTestsPerEvictionRun = url.getParameter("num.tests.per.eviction.run", 0);
        if (url.getParameter("time.between.eviction.runs.millis", 0) > 0)
            config.timeBetweenEvictionRunsMillis = url.getParameter("time.between.eviction.runs.millis", 0);
        if (url.getParameter("min.evictable.idle.time.millis", 0) > 0)
            config.minEvictableIdleTimeMillis = url.getParameter("min.evictable.idle.time.millis", 0);
        final JedisPool jedisPool = new JedisPool(config, url.getHost(), url.getPort(DEFAULT_PORT), url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT));
        final int expiry = url.getParameter("expiry", 0);
        final String get = url.getParameter("get", "get");
        final String set = url.getParameter("set", Map.class.equals(type) ? "put" : "set");
        final String delete = url.getParameter("delete", Map.class.equals(type) ? "remove" : "delete");
        return new AbstractInvoker<T>(type, url) {

            protected Result doInvoke(Invocation invocation) throws Throwable {
                Jedis resource = null;
                try {
                    resource = jedisPool.getResource();
                    if (get.equals(invocation.getMethodName())) {
                        if (invocation.getArguments().length != 1) {
                            throw new IllegalArgumentException("The redis get method arguments mismatch, must only one arguments. interface: " + type.getName() + ", method: " + invocation.getMethodName() + ", url: " + url);
                        }
                        byte[] value = resource.get(String.valueOf(invocation.getArguments()[0]).getBytes());
                        if (value == null) {
                            return new RpcResult();
                        }
                        ObjectInput oin = getSerialization(url).deserialize(url, new ByteArrayInputStream(value));
                        return new RpcResult(oin.readObject());
                    } else if (set.equals(invocation.getMethodName())) {
                        if (invocation.getArguments().length != 2) {
                            throw new IllegalArgumentException("The redis set method arguments mismatch, must be two arguments. interface: " + type.getName() + ", method: " + invocation.getMethodName() + ", url: " + url);
                        }
                        byte[] key = String.valueOf(invocation.getArguments()[0]).getBytes();
                        ByteArrayOutputStream output = new ByteArrayOutputStream();
                        ObjectOutput value = getSerialization(url).serialize(url, output);
                        value.writeObject(invocation.getArguments()[1]);
                        resource.set(key, output.toByteArray());
                        if (expiry > 1000) {
                            resource.expire(key, expiry / 1000);
                        }
                        return new RpcResult();
                    } else if (delete.equals(invocation.getMethodName())) {
                        if (invocation.getArguments().length != 1) {
                            throw new IllegalArgumentException("The redis delete method arguments mismatch, must only one arguments. interface: " + type.getName() + ", method: " + invocation.getMethodName() + ", url: " + url);
                        }
                        resource.del(String.valueOf(invocation.getArguments()[0]).getBytes());
                        return new RpcResult();
                    } else {
                        throw new UnsupportedOperationException("Unsupported method " + invocation.getMethodName() + " in redis service.");
                    }
                } catch (Throwable t) {
                    RpcException re = new RpcException("Failed to invoke redis service method. interface: " + type.getName() + ", method: " + invocation.getMethodName() + ", url: " + url + ", cause: " + t.getMessage(), t);
                    if (t instanceof TimeoutException || t instanceof SocketTimeoutException) {
                        re.setCode(RpcException.TIMEOUT_EXCEPTION);
                    } else if (t instanceof JedisConnectionException || t instanceof IOException) {
                        re.setCode(RpcException.NETWORK_EXCEPTION);
                    } else if (t instanceof JedisDataException) {
                        re.setCode(RpcException.SERIALIZATION_EXCEPTION);
                    }
                    throw re;
                } finally {
                    if (resource != null) {
                        try {
                            jedisPool.returnResource(resource);
                        } catch (Throwable t) {
                            logger.warn("returnResource error: " + t.getMessage(), t);
                        }
                    }
                }
            }

            public void destroy() {
                super.destroy();
                try {
                    jedisPool.destroy();
                } catch (Throwable e) {
                    logger.warn(e.getMessage(), e);
                }
            }
        };
    } catch (Throwable t) {
        throw new RpcException("Failed to refer redis service. interface: " + type.getName() + ", url: " + url + ", cause: " + t.getMessage(), t);
    }
}
Also used : Invocation(com.alibaba.dubbo.rpc.Invocation) ObjectOutput(com.alibaba.dubbo.common.serialize.ObjectOutput) RpcResult(com.alibaba.dubbo.rpc.RpcResult) AbstractInvoker(com.alibaba.dubbo.rpc.protocol.AbstractInvoker) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) GenericObjectPool(org.apache.commons.pool.impl.GenericObjectPool) JedisDataException(redis.clients.jedis.exceptions.JedisDataException) Jedis(redis.clients.jedis.Jedis) SocketTimeoutException(java.net.SocketTimeoutException) ByteArrayInputStream(java.io.ByteArrayInputStream) RpcException(com.alibaba.dubbo.rpc.RpcException) JedisPool(redis.clients.jedis.JedisPool) ObjectInput(com.alibaba.dubbo.common.serialize.ObjectInput) JedisConnectionException(redis.clients.jedis.exceptions.JedisConnectionException) TimeoutException(java.util.concurrent.TimeoutException) SocketTimeoutException(java.net.SocketTimeoutException)

Example 5 with JedisPool

use of redis.clients.jedis.JedisPool in project presto by prestodb.

the class EmbeddedRedis method start.

public void start() throws IOException {
    redisServer.start();
    jedisPool = new JedisPool(new JedisPoolConfig(), getConnectString(), getPort());
}
Also used : JedisPool(redis.clients.jedis.JedisPool) JedisPoolConfig(redis.clients.jedis.JedisPoolConfig)

Aggregations

JedisPool (redis.clients.jedis.JedisPool)72 Test (org.junit.Test)47 Jedis (redis.clients.jedis.Jedis)46 JedisPoolConfig (redis.clients.jedis.JedisPoolConfig)35 GenericObjectPoolConfig (org.apache.commons.pool2.impl.GenericObjectPoolConfig)16 URI (java.net.URI)5 HashSet (java.util.HashSet)5 LinkedHashSet (java.util.LinkedHashSet)5 HostAndPort (redis.clients.jedis.HostAndPort)5 JedisCluster (redis.clients.jedis.JedisCluster)5 RpcException (com.alibaba.dubbo.rpc.RpcException)4 URISyntaxException (java.net.URISyntaxException)4 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)4 JedisException (redis.clients.jedis.exceptions.JedisException)4 HashMap (java.util.HashMap)3 Map (java.util.Map)3 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)3 ConcurrentMap (java.util.concurrent.ConcurrentMap)3 InvalidURIException (redis.clients.jedis.exceptions.InvalidURIException)3 ArrayList (java.util.ArrayList)2