Java GenericObjectPool オブジェクト プーリング テクノロジの使用方法
Java BasePooledObjectFactory オブジェクト プーリング テクノロジ
通常、オブジェクトの作成と破棄に非常に時間がかかる場合、オブジェクトを頻繁に作成および破棄することはありませんが、再利用を検討します。オブジェクトを再利用する方法の1つがオブジェクトプーリングです。作成したオブジェクトをプールに入れて管理し、次回利用するときはプール内に作成したオブジェクトをそのまま利用して使い続けることができる、という考え方です。プーリングの。
Apache Commons Pool は、オブジェクト プーリングを実装するための API の完全なセットを提供するオブジェクト プール フレームワークです。 GenericKeyedObjectPool、SoftReferenceObjectPool、GenericObjectPool の 3 種類のオブジェクト プールが提供されます。GenericObjectPool は最も一般的に使用されるオブジェクト プールであり、その内部実装も最も複雑です。
GenericObjectPool
GenericObjectPool は、堅牢なオブジェクト プールを実装できる汎用オブジェクト プール フレームワークです。UML 図は次のとおりです:
GenericObjectPool は ObjectPool インターフェイスを実装します。ObjectPool はオブジェクト プールのコア インターフェイスであり、オブジェクト プールが実装する必要がある動作を定義します。
public interface ObjectPool<T> extends Closeable { /** * 从池中借走到一个对象 */ T borrowObject() throws Exception, NoSuchElementException, IllegalStateException; /** * 把对象归还给对象池 */ void returnObject(T var1) throws Exception; /** * 验证对象的有效性 */ void invalidateObject(T var1) throws Exception; /** * 往池中添加一个对象 */ void addObject() throws Exception, IllegalStateException, UnsupportedOperationException; /** * 返回对象池中有多少对象是空闲的,也就是能够被借走的对象的数量。 */ int getNumIdle(); /** * 返回对象池中有对象对象是活跃的,也就是已经被借走的,在使用中的对象的数量。 */ int getNumActive(); /** * 清理对象池。注意是清理不是清空,该方法要求的是,清理所有空闲对象,释放相关资源。 */ void clear() throws Exception, UnsupportedOperationException; /** * 关闭对象池。这个方法可以达到清空的效果,清理所有对象以及相关资源。 */ void close(); }
BasePooledObjectFactory
Java BasePooledObjectFactory オブジェクト プーリング テクノロジー
GenericObjectPool
を使用するには、オブジェクト ファクトリ クラスを作成し、BasePooledObjectFactory# を継承するだけです。 ## そして、その
create() と
destroyObject() をオーバーライドします。
次のように:
SftpPool.java
public interface PooledObjectFactory<T> { /** * 创建一个可由池提供服务的实例,并将其封装在由池管理的PooledObject中。 */ PooledObject<T> makeObject() throws Exception; /** * 销毁池不再需要的实例 */ void destroyObject(PooledObject<T> var1) throws Exception; /** * 确保实例可以安全地由池返回 */ boolean validateObject(PooledObject<T> var1); /** * 重新初始化池返回的实例 */ void activateObject(PooledObject<T> var1) throws Exception; /** * 取消初始化要返回到空闲对象池的实例 */ void passivateObject(PooledObject<T> var1) throws Exception; }
GenericObjectPoolConfig はカプセル化
GenericObjectプール設定 単純な「構造体」であるこのクラスはスレッドセーフではなく、プールの作成時に使用されるプロパティを提供するためにのみ使用されます。ほとんどの場合、
GenericObjectPoolConfig によって提供されるデフォルトのパラメーターを使用して、日々のニーズを満たすことができます。
- ##構築方法
- 構築方法を実行する際の主な仕事は、オブジェクトを格納する LinkedList 型のコンテナを作成することです。これは概念的なものです。
- borrowObject() コマンドを使用してプール内のオブジェクトを取得します。ソース コードはさらに複雑です。簡単に言うと、 LinkedList から取得する方法です。オブジェクトが存在しない場合は、コンストラクターの最初のパラメーター Factory クラスの makeObject() メソッドを呼び出してオブジェクトを作成し、取得します。オブジェクトを取得した後、validateObject メソッドを呼び出す必要があります。オブジェクトが使用可能かどうかを判断します。使用可能な場合は、使用可能なもののみを使用します。 LinkedList コンテナから 1 を引いた値
- 簡単に言うと、 validateObject メソッドを呼び出して、オブジェクトが利用可能かどうかを確認します。利用可能な場合は、オブジェクトを返します。 LinkedList コンテナーをプールに追加します (それが不可能な場合は、destroyObject メソッドを呼び出して破棄します)
#取得と返却の処理手順が異なるため、上記の 3 つの手順が最も単純なプロセスです。は、borrowObject メソッドと returnObject メソッドで修正されているため、Factory クラスの makeObject()、validateObject、destroyObject メソッドを書き換えるだけで、最も単純なプール管理制御を実現できます。コンストラクター メソッドを介して Factory クラスのオブジェクトを渡すことで、次のことができます。最も単純なオブジェクト プール管理クラスを作成します。これはより適切な分離設計パターンであり、借用と返却のプロセスは次の図に示すとおりです。 #<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> <version>2.7.0</version> </dependency> <!-- https://mvnrepository.com/artifact/com.jcraft/jsch --> <dependency> <groupId>com.jcraft</groupId> <artifactId>jsch</artifactId> <version>0.1.55</version> </dependency>
ログイン後にコピーSftpPoolException.java
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>vipsoft-parent</artifactId> <groupId>com.vipsoft.boot</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>vipsoft-sftp</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> <version>2.7.0</version> </dependency> <!-- https://mvnrepository.com/artifact/com.jcraft/jsch --> <dependency> <groupId>com.jcraft</groupId> <artifactId>jsch</artifactId> <version>0.1.55</version> </dependency> <dependency> <groupId>org.eclipse.paho</groupId> <artifactId>org.eclipse.paho.client.mqttv3</artifactId> <version>1.2.5</version> </dependency> <dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.3.6</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
config
SftpConfig.java
server: port: 8088 application: name: sftp Demo sftp: host: 172.16.3.88 # 服务器ip port: 22 # ssh端口 username: root # 用户名 password: root # 密码 # 连接池参数 pool: max-total: 10 max-idle: 10 min-idle: 5
package com.vipsoft.sftp.exception;
/**
* sftp连接池异常
*/
public class SftpPoolException extends RuntimeException {
private static final long serialVersionUID = 1L;
/**
* Constructs a new runtime exception with {@code null} as its
* detail message. The cause is not initialized, and may subsequently be
* initialized by a call to {@link #initCause}.
*/
public SftpPoolException() {
}
/**
* Constructs a new runtime exception with the specified detail message.
* The cause is not initialized, and may subsequently be initialized by a
* call to {@link #initCause}.
*
* @param message the detail message. The detail message is saved for
* later retrieval by the {@link #getMessage()} method.
*/
public SftpPoolException(String message) {
super(message);
}
/**
* Constructs a new runtime exception with the specified detail message and
* cause. <p>Note that the detail message associated with
* {@code cause} is <i>not</i> automatically incorporated in
* this runtime exception's detail message.
*
* @param message the detail message (which is saved for later retrieval
* by the {@link #getMessage()} method).
* @param cause the cause (which is saved for later retrieval by the
* {@link #getCause()} method). (A <tt>null</tt> value is
* permitted, and indicates that the cause is nonexistent or
* unknown.)
* @since 1.4
*/
public SftpPoolException(String message, Throwable cause) {
super(message, cause);
}
/**
* Constructs a new runtime exception with the specified cause and a
* detail message of <tt>(cause==null ? null : cause.toString())</tt>
* (which typically contains the class and detail message of
* <tt>cause</tt>). This constructor is useful for runtime exceptions
* that are little more than wrappers for other throwables.
*
* @param cause the cause (which is saved for later retrieval by the
* {@link #getCause()} method). (A <tt>null</tt> value is
* permitted, and indicates that the cause is nonexistent or
* unknown.)
* @since 1.4
*/
public SftpPoolException(Throwable cause) {
super(cause);
}
/**
* Constructs a new runtime exception with the specified detail
* message, cause, suppression enabled or disabled, and writable
* stack trace enabled or disabled.
*
* @param message the detail message.
* @param cause the cause. (A {@code null} value is permitted,
* and indicates that the cause is nonexistent or unknown.)
* @param enableSuppression whether or not suppression is enabled
* or disabled
* @param writableStackTrace whether or not the stack trace should
* be writable
* @since 1.7
*/
public SftpPoolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
ログイン後にコピー
PoolSftpFactory .javapackage com.vipsoft.sftp.exception; /** * sftp连接池异常 */ public class SftpPoolException extends RuntimeException { private static final long serialVersionUID = 1L; /** * Constructs a new runtime exception with {@code null} as its * detail message. The cause is not initialized, and may subsequently be * initialized by a call to {@link #initCause}. */ public SftpPoolException() { } /** * Constructs a new runtime exception with the specified detail message. * The cause is not initialized, and may subsequently be initialized by a * call to {@link #initCause}. * * @param message the detail message. The detail message is saved for * later retrieval by the {@link #getMessage()} method. */ public SftpPoolException(String message) { super(message); } /** * Constructs a new runtime exception with the specified detail message and * cause. <p>Note that the detail message associated with * {@code cause} is <i>not</i> automatically incorporated in * this runtime exception's detail message. * * @param message the detail message (which is saved for later retrieval * by the {@link #getMessage()} method). * @param cause the cause (which is saved for later retrieval by the * {@link #getCause()} method). (A <tt>null</tt> value is * permitted, and indicates that the cause is nonexistent or * unknown.) * @since 1.4 */ public SftpPoolException(String message, Throwable cause) { super(message, cause); } /** * Constructs a new runtime exception with the specified cause and a * detail message of <tt>(cause==null ? null : cause.toString())</tt> * (which typically contains the class and detail message of * <tt>cause</tt>). This constructor is useful for runtime exceptions * that are little more than wrappers for other throwables. * * @param cause the cause (which is saved for later retrieval by the * {@link #getCause()} method). (A <tt>null</tt> value is * permitted, and indicates that the cause is nonexistent or * unknown.) * @since 1.4 */ public SftpPoolException(Throwable cause) { super(cause); } /** * Constructs a new runtime exception with the specified detail * message, cause, suppression enabled or disabled, and writable * stack trace enabled or disabled. * * @param message the detail message. * @param cause the cause. (A {@code null} value is permitted, * and indicates that the cause is nonexistent or unknown.) * @param enableSuppression whether or not suppression is enabled * or disabled * @param writableStackTrace whether or not the stack trace should * be writable * @since 1.7 */ public SftpPoolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } }
package com.vipsoft.sftp.config; import com.vipsoft.sftp.pool.SftpFactory; import com.vipsoft.sftp.pool.SftpPool; import com.vipsoft.sftp.utils.SftpUtil; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration @EnableConfigurationProperties(SftpProperties.class) public class SftpConfig { // 工厂 @Bean public SftpFactory sftpFactory(SftpProperties properties) { return new SftpFactory(properties); } // 连接池 @Bean public SftpPool sftpPool(SftpFactory sftpFactory) { return new SftpPool(sftpFactory); } // 辅助类 @Bean public SftpUtil sftpUtil(SftpPool sftpPool) { return new SftpUtil(sftpPool); } }
package com.vipsoft.sftp.config;
import com.jcraft.jsch.ChannelSftp;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "sftp")
public class SftpProperties {
private String host;
private int port = 22;
private String username = "root";
private String password = "root";
private Pool pool = new Pool();
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Pool getPool() {
return pool;
}
public void setPool(Pool pool) {
this.pool = pool;
}
public static class Pool extends GenericObjectPoolConfig<ChannelSftp> {
private int maxTotal = DEFAULT_MAX_TOTAL;
private int maxIdle = DEFAULT_MAX_IDLE;
private int minIdle = DEFAULT_MIN_IDLE;
public Pool() {
super();
}
@Override
public int getMaxTotal() {
return maxTotal;
}
@Override
public void setMaxTotal(int maxTotal) {
this.maxTotal = maxTotal;
}
@Override
public int getMaxIdle() {
return maxIdle;
}
@Override
public void setMaxIdle(int maxIdle) {
this.maxIdle = maxIdle;
}
@Override
public int getMinIdle() {
return minIdle;
}
@Override
public void setMinIdle(int minIdle) {
this.minIdle = minIdle;
}
}
}
ログイン後にコピー
UtilsByteUtil.javapackage com.vipsoft.sftp.config; import com.jcraft.jsch.ChannelSftp; import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import org.springframework.boot.context.properties.ConfigurationProperties; @ConfigurationProperties(prefix = "sftp") public class SftpProperties { private String host; private int port = 22; private String username = "root"; private String password = "root"; private Pool pool = new Pool(); public String getHost() { return host; } public void setHost(String host) { this.host = host; } public int getPort() { return port; } public void setPort(int port) { this.port = port; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Pool getPool() { return pool; } public void setPool(Pool pool) { this.pool = pool; } public static class Pool extends GenericObjectPoolConfig<ChannelSftp> { private int maxTotal = DEFAULT_MAX_TOTAL; private int maxIdle = DEFAULT_MAX_IDLE; private int minIdle = DEFAULT_MIN_IDLE; public Pool() { super(); } @Override public int getMaxTotal() { return maxTotal; } @Override public void setMaxTotal(int maxTotal) { this.maxTotal = maxTotal; } @Override public int getMaxIdle() { return maxIdle; } @Override public void setMaxIdle(int maxIdle) { this.maxIdle = maxIdle; } @Override public int getMinIdle() { return minIdle; } @Override public void setMinIdle(int minIdle) { this.minIdle = minIdle; } } }
package com.vipsoft.sftp.pool; import com.jcraft.jsch.ChannelSftp; import com.jcraft.jsch.JSch; import com.jcraft.jsch.JSchException; import com.jcraft.jsch.Session; import com.vipsoft.sftp.config.SftpProperties; import com.vipsoft.sftp.exception.SftpPoolException; import org.apache.commons.pool2.BasePooledObjectFactory; import org.apache.commons.pool2.PooledObject; import org.apache.commons.pool2.impl.DefaultPooledObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Properties; public class SftpFactory extends BasePooledObjectFactory<ChannelSftp> { private final Logger logger = LoggerFactory.getLogger(this.getClass()); private SftpProperties properties; public SftpProperties getProperties() { return properties; } public void setProperties(SftpProperties properties) { this.properties = properties; } public SftpFactory(SftpProperties properties) { this.properties = properties; } @Override public ChannelSftp create() { try { JSch jsch = new JSch(); Session sshSession = jsch.getSession(properties.getUsername(), properties.getHost(), properties.getPort()); sshSession.setPassword(properties.getPassword()); Properties sshConfig = new Properties(); sshConfig.put("StrictHostKeyChecking", "no"); sshSession.setConfig(sshConfig); sshSession.connect(); ChannelSftp channel = (ChannelSftp) sshSession.openChannel("sftp"); channel.connect(); return channel; } catch (JSchException e) { throw new SftpPoolException("连接sfpt失败", e); } } @Override public PooledObject<ChannelSftp> wrap(ChannelSftp channelSftp) { return new DefaultPooledObject<>(channelSftp); } // 销毁对象 @Override public void destroyObject(PooledObject<ChannelSftp> p) { ChannelSftp channelSftp = p.getObject(); channelSftp.disconnect(); } }
package com.vipsoft.sftp.pool; import com.jcraft.jsch.ChannelSftp; import org.apache.commons.pool2.impl.GenericObjectPool; public class SftpPool<T> extends GenericObjectPool<ChannelSftp> { public SftpPool(SftpFactory factory) { super(factory,factory.getProperties().getPool()); } /** * 获取一个sftp连接对象 * @return sftp连接对象 */ @Override public ChannelSftp borrowObject() throws Exception { return super.borrowObject(); } /** * 归还一个sftp连接对象 * @param channelSftp sftp连接对象 */ @Override public void returnObject(ChannelSftp channelSftp) { if (channelSftp!=null) { super.returnObject(channelSftp); } } }
以上がJava GenericObjectPool オブジェクト プーリング テクノロジの使用方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

AI Hentai Generator
AIヘンタイを無料で生成します。

人気の記事

ホットツール

メモ帳++7.3.1
使いやすく無料のコードエディター

SublimeText3 中国語版
中国語版、とても使いやすい

ゼンドスタジオ 13.0.1
強力な PHP 統合開発環境

ドリームウィーバー CS6
ビジュアル Web 開発ツール

SublimeText3 Mac版
神レベルのコード編集ソフト(SublimeText3)

ホットトピック









Java のアームストロング番号に関するガイド。ここでは、Java でのアームストロング数の概要とコードの一部について説明します。

Java の乱数ジェネレーターのガイド。ここでは、Java の関数について例を挙げて説明し、2 つの異なるジェネレーターについて例を挙げて説明します。

Java の Weka へのガイド。ここでは、weka java の概要、使い方、プラットフォームの種類、利点について例を交えて説明します。

この記事では、Java Spring の面接で最もよく聞かれる質問とその詳細な回答をまとめました。面接を突破できるように。

Java 8は、Stream APIを導入し、データ収集を処理する強力で表現力のある方法を提供します。ただし、ストリームを使用する際の一般的な質問は次のとおりです。 従来のループにより、早期の中断やリターンが可能になりますが、StreamのForeachメソッドはこの方法を直接サポートしていません。この記事では、理由を説明し、ストリーム処理システムに早期終了を実装するための代替方法を調査します。 さらに読み取り:JavaストリームAPIの改善 ストリームを理解してください Foreachメソッドは、ストリーム内の各要素で1つの操作を実行する端末操作です。その設計意図はです
