当前位置: 首页 > 面试题库 >

在GenericObjectPool中创建对象

柳俊彦
2023-03-14
问题内容

我正在GenericObjectPool通过放入Cipher池中进行研究,以便可以重复使用它。

GenericObjectPool<Cipher> pool;

CipherFactory factory = new CipherFactory(); 
this.pool = new GenericObjectPool<Cipher>(factory);
pool.setMaxTotal(10);
pool.setBlockWhenExhausted(true);
pool.setMaxWaitMillis(30 * 1000);

密码工厂

public class CipherFactory extends BasePooledObjectFactory<Cipher> {

    private boolean running = false;

    @Override
    public Cipher create() throws Exception {
        return Cipher.getInstance("DESede/CBC/NoPadding");
    }

    @Override
    public PooledObject<Cipher> wrap(Cipher arg0) {
        return new DefaultPooledObject<Cipher>(arg0);
    }

    @Override
    public boolean validateObject(PooledObject<Cipher> p) {
        //Ensures that the instance is safe to be returned by the pool
        return true;
    }

    @Override
    public void destroyObject(PooledObject<Cipher> p) {
        //Destroys an instance no longer needed by the pool. 
        System.out.println("destroying");
    }

    @Override
    public void activateObject(PooledObject<Cipher> p) throws Exception { //Reinitialize an instance to be returned by the pool

        setRunning(true);
    }

    @Override
    public void passivateObject(PooledObject<Cipher> p) throws Exception {   // reset the object after the object returns to the pool

        setRunning(false);
    }

    public void setRunning(boolean running) {

        this.running = running;
    }
//    
}

这就是我ObjectPoolExample 类中实现的方式

public Key a(byte[] afyte) throws Exception {

        Cipher cipher = null;
        cipher = pool.borrowObject(); //get the object from the pool
        try {
            System.out.println("****************** After borrow ****************");
            printPool();
            cipher.init(Cipher.DECRYPT_MODE, mkkey, algParamSpec);
            byte[] de = cipher.doFinal(afyte);
            SecretKey mk = new SecretKeySpec(de, "DESede");
            return mk;
        } catch (Exception e) {
            pool.invalidateObject(cipher);
            cipher = null;
        } finally {
            if (null != cipher) {
                pool.returnObject(cipher);
                System.out.println("****************** After return ****************");
                printPool();
            }
        }
        return (Key) cipher;
    }

打印池

public void printPool() {
        System.out.println("Pool for cipher with instances DESede/CBC/NoPadding");
        System.out.println("Active [" + pool.getNumActive() + "]"); //Return the number of instances currently borrowed from this pool
        System.out.println("Idle [" + pool.getNumIdle() + "]"); //The number of instances currently idle in this pool
        System.out.println("Total Created [" + pool.getCreatedCount() + "]");      
    }

我在正确的道路上吗?是否可以增加泳池大小?

编辑

@http的答案对我来说很好。但是,如果我有另一种方法encryptECB(Key key, byte[] b),应该怎么写?

任何帮助,将不胜感激 !


问题答案:

您走在正确的轨道上。构造GenericObjectPool时,可以使用接受GenericObjectPoolConfig对象的构造函数,该对象包含对象池的所有配置值。下面的示例将使您的池在耗尽之前增加到20个连接…

GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.setMinIdle(2);
config.setMaxIdle(5);
config.setMaxTotal(20);

GenericObjectPool<Cipher> pool;
CipherFactory factory = new CipherFactory(); 
this.pool = new GenericObjectPool<Cipher>(factory, config);

GenericeObjectPoolConfig还具有setBlockWhenExhausted方法,用于指定池达到maxTotal连接时的行为。有关详细信息,请参见https://commons.apache.org/proper/commons-
pool/apidocs/org/apache/commons/pool2/impl/BaseObjectPoolConfig.html#setBlockWhenExhausted-
boolean-

我在使用Commons Pool时实现的一种模式是创建2个接口,一个用于您的池对象,一个用于您的工厂…

public interface PooledCipher extends java.io.Closeable {
    byte[] doFinal(byte[] bytes) throws Exception;
    SecretKeySpec getSecretKeySpec(byte[] bytes) throws Exception;
}

public interface CipherFactory {
    PooledCipher getCipher() throws Exception;        
    void close();
}

CipherFactory的实现…

public class CipherFactoryImpl extends BasePooledObjectFactory<PooledCipher> 
    implements CipherFactory {

    private final GenericObjectPoolConfig config;
    private final GenericObjectPool<PooledCipher> pool;
    private final String transformation;
    private final int opmode;
    private final Key key;
    private final AlgorithmParameters params;
    private final String secretKeySpecAlgorithm;

    public CipherFactoryImpl(GenericObjectPoolConfig config, String transformation, int opmode, Key key, AlgorithmParameters params, String secretKeySpecAlgorithm) {
        this.config = config;
        this.pool = new GenericObjectPool<PooledCipher>(this, config);
        this.transformation = transformation;
        this.opmode = opmode;
        this.key = key;
        this.params = params;       
        this.secretKeySpecAlgorithm = secretKeySpecAlgorithm
    }

    @Override
    public PooledCipher create() throws Exception {
        return new PooledCipherImpl(pool, transformation, opmode, key, params, secretKeySpecAlgorithm);
    }

    @Override
    public PooledCipher getCipher() throws Exception {
        return pool.borrowObject();
    }

    @Override
    public void destroyObject(PooledObject<PooledCipher> p) throws Exception {
        try {
            PooledCipherImpl cipherImpl = (PooledCipherImpl)p.getObject();
            // do whatever you need with cipherImpl to destroy it
        } finally {
            super.destroyObject(p);
        }
    }

    @Override
    public void close() {
        pool.close();
    }

    @Override
    public PooledObject<PooledCipher> wrap(PooledCipher cipher) {
        return new DefaultPooledObject<PooledCipher>(cipher);
    }
}

PooledCipher实现…

public class PooledCipherImpl implements PooledCipher {
    private final ObjectPool<PooledCipher> pool;
    private final Cipher cipher;
    private final String secretKeySpecAlgorithm;
    private boolean destroyOnClose = false;

    public PooledCipherImpl(ObjectPool<PooledCipher> pool, String transformation, int opmode, Key key, AlgorithmParameters params, String secretKeySpecAlgorithm) {
        this.pool = pool;
        this.cipher = Cipher.getInstance(transformation);
        this.cipher.init(opmode, key, params);
        this.secretKeySpecAlgorithm = secretKeySpecAlgorithm;
    }

    @Override
    public byte[] doFinal(byte[] bytes) throws Exception {
        try {
            return cipher.doFinal(bytes);
        } catch (Exception e) {
           destroyOnClose = true;
           throw e;
        }
    }

    @Override
    public SecretKeySpec getSecretKeySpec(byte[] bytes) {
        return new SecretKeySpec(doFinal(bytes), secretKeySpecAlgorithm);
    }

    @Override
    public void close() throws IOException {
        try {
            if (destroyOnClose) {
                pool.destroyObject(this);
            } else {
                pool.returnObject(this);
            }
        } catch (Exception e) {
            throw new IOException(e);
        }
    }
}

然后您像这样构造您的CipherFactory …

String transformation = "DESede/CBC/NoPadding";
String secretKeySpecAlgorithm = "DESede";
GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
// set up the poolConfig here
poolConfig.setMaxTotal(20);
CipherFactory cipherFactory = new CipherFactoryImpl(poolConfig, transformation, Cipher.DECRYPT_MODE, mkkey, algParamSpec, secretKeySpecAlgorithm);

并像这样使用它…

public Key unwrapKey(byte[] tmkByte) throws Exception {
    try (PooledCipher cipher = cipherFactory.getCipher()) {
        return cipher.getSecretKeySpec(tmkByte);
    }
}

您也可以重用PooledCipher和CipherFactory接口来创建其他实现,例如JCA。



 类似资料:
  • 问题内容: 众所周知,使用JavaScript创建匿名对象很容易,就像下面的代码一样: 输出: 可以在PHP中应用相同的技术吗?我们可以在PHP中创建匿名对象吗? 问题答案: 已经有好几年了,但是我认为我需要保持最新信息! 从PHP 7开始,可以创建匿名类,因此您可以执行以下操作: 您可以在手册中详细了解 但是我不知道它的实现与JavaScript有多么相似,因此JavaScript和PHP中的匿

  • 我遇到了一些Java代码: 在Java中,我第一次遇到一个构造函数或方法,它的参数是一个接口的“类型”。可以创建接口的对象吗?你能像普通物体一样使用它们吗? 在C语言中,我知道创建抽象类的对象是不可能的。

  • 我需要创建一个对象(银行),其中包含一组客户端和bankID。我的问题是,我不知道如何在主函数中创建银行。 银行类别: 客户端类: 主要类别: 这些是问题所在: 你必须创建一个程序来模拟银行活动。该系统包括以下模块:银行—客户(客户数组)— idBank(字符串)5 BancAccount — accountNumber(字符串)—金额(浮点)客户—姓名(字符串)—地址(字符串)—账户(银行账户数

  • 问题内容: 我正在尝试kafka.utils.ZKStringSerializer用clojure创建一个scala对象。(在org.apache.kafka/kafka_2.10 “0.8.0”) 由于我对scala知之甚少,所以我不知道如何调用它的构造函数。我这样尝试过: 并得到一个错误: 我尝试使用来查看其方法,但是只有一些静态方法。并告诉我这是一类,而不是我想要的实例。 该对象的实现如下:

  • 本文向大家介绍如何在Java中创建String对象?,包括了如何在Java中创建String对象?的使用技巧和注意事项,需要的朋友参考一下 您可以通过以下方式创建字符串: 将包装在“”中的字符串值分配给String类型变量。 通过将字符串值作为其构造函数的参数传递,使用new关键字创建String类的对象。 将字符数组传递给String构造函数。

  • 本文向大家介绍如何在Python中创建类对象?,包括了如何在Python中创建类对象?的使用技巧和注意事项,需要的朋友参考一下 使用该类的构造函数创建一个类对象。然后将该对象称为类的实例。类实例化使用函数表示法。  在下面的代码中,我们定义一个类并创建了相同类的实例,如下所示