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

io.milvus.pool.PoolClientFactory Maven / Gradle / Ivy

There is a newer version: 2.4.8
Show newest version
package io.milvus.pool;

import org.apache.commons.pool2.BaseKeyedPooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

public class PoolClientFactory extends BaseKeyedPooledObjectFactory {
    protected static final Logger logger = LoggerFactory.getLogger(PoolClientFactory.class);
    private final C config;
    private Constructor constructor;
    private Method closeMethod;
    private Method verifyMethod;

    public PoolClientFactory(C config, String clientClassName) throws ClassNotFoundException, NoSuchMethodException {
        this.config = config;
        try {
            Class clientCls = Class.forName(clientClassName);
            Class configCls = Class.forName(config.getClass().getName());
            constructor = clientCls.getConstructor(configCls);
            closeMethod = clientCls.getMethod("close", long.class);
            verifyMethod = clientCls.getMethod("clientIsReady");
        } catch (Exception e) {
            logger.error("Failed to create client pool factory, exception: ", e);
            throw e;
        }
    }

    @Override
    public T create(String key) throws Exception {
        try {
            T client = (T) constructor.newInstance(this.config);
            return client;
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public PooledObject wrap(T client) {
        return new DefaultPooledObject<>(client);
    }

    @Override
    public void destroyObject(String key, PooledObject p) throws Exception {
        T client = p.getObject();
        closeMethod.invoke(client, 3L);
    }

    @Override
    public boolean validateObject(String key, PooledObject p) {
        try {
            T client = p.getObject();
            return (boolean) verifyMethod.invoke(client);
        } catch (Exception e) {
            logger.error("Failed to validate client, exception: " + e);
            return true;
        }
    }

    @Override
    public void activateObject(String key, PooledObject p) throws Exception {
        super.activateObject(key, p);
    }

    @Override
    public void passivateObject(String key, PooledObject p) throws Exception {
        super.passivateObject(key, p);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy