从零学spring boot-集成redis时未使用连接池的问题

在之前spring boot集成redis的文章中曾今指出如果没有配置redis连接池的信息(即使存在默认的连接信息),那么在使用redisTemplate的时候,是不会使用连接池的。这一篇文章我们将从源码中分析这其中的原因。

首先我们需要看一下redisTemplate获取redis连接的源码:

//redisTemplate获取连接实际上是通过JedisConnectionFactory来获取的
protected Jedis fetchJedisConnector() {
	try {
        //由这里可以看出,如果pool对象为null,那么每次都只能去new了
		if (getUsePool() && pool != null) {
			return pool.getResource();
		}

		Jedis jedis = createJedis();
		……
	}
}

通过上面的代码,我们可以看出,jedisConnectionFactory中的pool对象是关键,那么我们再来看一下这个pool对象是在哪里初始化的吧,spring data redis做了自动配置功能,代码的入口在JedisConnectionConfiguration,跟踪代码,我们最后看到如下代码:

private JedisClientConfiguration getJedisClientConfiguration() {
	JedisClientConfigurationBuilder builder = applyProperties(
			JedisClientConfiguration.builder());
	RedisProperties.Pool pool = this.properties.getJedis().getPool();
	if (pool != null) {
		applyPooling(pool, builder);
	}
	if (StringUtils.hasText(this.properties.getUrl())) {
		customizeConfigurationFromUrl(builder);
	}
	customize(builder);
	return builder.build();
}

我们发现pool对象是存在于properties对象中的,这个properties对象又是通过配置文件初始化的,通过分析properties对象,我们发现:

1. pool对象是Jedis对象的一个属性
2. pool对象中的属性都有默认值
3. Jedis并没有默认初始化pool对象

一下是Jedis对象的源码:

public static class Jedis {

	/**
	 * Jedis pool configuration.
	 */
	private Pool pool;

	public Pool getPool() {
		return this.pool;
	}

	public void setPool(Pool pool) {
		this.pool = pool;
	}

}

到这里我们就知道为什么pool对象为null了:

1. Jedis对象默认是不会初始化pool对象的
2. 当我们在配置文件中配置了poold对象的属性的时候,pool对象就会初始化

所以如果在配置文件中没有配置连接池的信息,最后是不会使用连接池的

发布了81 篇原创文章 · 获赞 16 · 访问量 20万+

猜你喜欢

转载自blog.csdn.net/mazhen1991/article/details/101103101