连接池和数据库可用性

时间:2016-11-23 03:20:55

标签: spring database-connection connection-pooling couchbase

如果我有一个到DB的连接池并重新启动数据库,则连接将变为无效。为什么?数据库主机名未更改。如何检测此情况并清除无效连接? 在我的案例中DB是Couchbase,但我认为这是一个普遍的问题。我们将Spring框架与Couchbase Java客户端一起用于以下方面。

Couchbase配置:

@Configuration
public class CouchbaseConfiguration {
    private Cluster cluster;

    @Value("${couchbase.nodes}")
    @Setter(AccessLevel.PACKAGE)
    private String nodes;

    @Value("${couchbase.adminUsername}")
    private String adminUsername;

    @Value("${couchbase.adminPassword}")
    private String adminPassword;

    private static final long CONNECT_TIMEOUT = TimeUnit.SECONDS.toMillis(10);

    @Setter(AccessLevel.PACKAGE)
    private Func2<CouchbaseEnvironment, List<String>, Cluster> clusterFactory = CouchbaseCluster::create; //NOPMD

    @PostConstruct
    void postConstruct() {
        List<String> nodes = asList(this.nodes.split(",")).stream().map(String::trim).collect(toList());

        CouchbaseEnvironment env = DefaultCouchbaseEnvironment.builder().connectTimeout(CONNECT_TIMEOUT)
                .bootstrapCarrierEnabled(false).build();

        cluster = clusterFactory.call(env, nodes);
    }

    @Bean
    Cluster cluster() {
        return cluster;
    }

    @Bean
    ClusterManager clusterManager() {
        return cluster.clusterManager(adminUsername, adminPassword);
    }

    @PreDestroy
    void preDestroy() {
        cluster.disconnect();
    }
}

Couchbase用法:

@Autowired
private Cluster cluster;

@Bean
Bucket bucket() {
    return cluster.openBucket(bucketName, bucketPassword);
}

0 个答案:

没有答案