Jedis配置参数

      最近看到有人在使用jedis链接redis时,出现链接超时的情况,因此看了看jedis在代码中参数的作用.

      jedis的配置参数主要用于pool中,目前默认采用的是GenericObjectPool类中。看类的说明文档就已经很明白了.

      主要的参数有一下几个:

     maxActive      最大链接数

     maxIdle          最小链接数

    whenExhaustedAction    这是pool用尽时,jedis的行为配置,默认为 WHEN_EXHAUSTED_BLOCK ,也就是阻塞,等待pool中有可用的链接,阻塞时间有maxWait设置,如果值为小于0,则无线阻塞,知道有可用链接。

                                             其他的行为有,WHEN_EXHAUSTED_FAIL (直接抛出异常),WHEN_EXHAUSTED_GROW(新建一个连接)

   maxWait

   testOnBorrow   ,获取连接之前,是否测试连接可用,默认是false。网络不稳定的情况,可以采用true,如果测试不通过,从pool中移除,并再次执行获取连接。

  testOnReturn  ,  返回连接时,是否测试连接可用,默认是false。

  

  另外还有一部分配置pool队列,已经对pool中空闲的连接进行验证的配置参数,跟c3p0等连接池没有太多差异.


     原文如下:

  * A <tt>GenericObjectPool</tt> provides a number of configurable parameters:
 * <ul>
 *  <li>
 *    {@link #setMaxActive <i>maxActive</i>} controls the maximum number of
 *    objects that can be allocated by the pool (checked out to clients, or
 *    idle awaiting checkout) at a given time.  When non-positive, there is no
 *    limit to the number of objects that can be managed by the pool at one time.
 *    When {@link #setMaxActive <i>maxActive</i>} is reached, the pool is said
 *    to be exhausted. The default setting for this parameter is 8.
 *  </li>
 *  <li>
 *    {@link #setMaxIdle <i>maxIdle</i>} controls the maximum number of objects
 *    that can sit idle in the pool at any time.  When negative, there is no
 *    limit to the number of objects that may be idle at one time. The default
 *    setting for this parameter is 8.
 *  </li>
 *  <li>
 *    {@link #setWhenExhaustedAction <i>whenExhaustedAction</i>} specifies the
 *    behavior of the {@link #borrowObject} method when the pool is exhausted:
 *    <ul>
 *    <li>
 *      When {@link #setWhenExhaustedAction <i>whenExhaustedAction</i>} is
 *      {@link #WHEN_EXHAUSTED_FAIL}, {@link #borrowObject} will throw
 *      a {@link NoSuchElementException}
 *    </li>
 *    <li>
 *      When {@link #setWhenExhaustedAction <i>whenExhaustedAction</i>} is
 *      {@link #WHEN_EXHAUSTED_GROW}, {@link #borrowObject} will create a new
 *      object and return it (essentially making {@link #setMaxActive <i>maxActive</i>}
 *      meaningless.)
 *    </li>
 *    <li>
 *      When {@link #setWhenExhaustedAction <i>whenExhaustedAction</i>}
 *      is {@link #WHEN_EXHAUSTED_BLOCK}, {@link #borrowObject} will block
 *      (invoke {@link Object#wait()}) until a new or idle object is available.
 *      If a positive {@link #setMaxWait <i>maxWait</i>}
 *      value is supplied, then {@link #borrowObject} will block for at
 *      most that many milliseconds, after which a {@link NoSuchElementException}
 *      will be thrown.  If {@link #setMaxWait <i>maxWait</i>} is non-positive,
 *      the {@link #borrowObject} method will block indefinitely.
 *    </li>
 *    </ul>
 *    The default <code>whenExhaustedAction</code> setting is
 *    {@link #WHEN_EXHAUSTED_BLOCK} and the default <code>maxWait</code>
 *    setting is -1. By default, therefore, <code>borrowObject</code> will
 *    block indefinitely until an idle instance becomes available.
 *  </li>
 *  <li>
 *    When {@link #setTestOnBorrow <i>testOnBorrow</i>} is set, the pool will
 *    attempt to validate each object before it is returned from the
 *    {@link #borrowObject} method. (Using the provided factory's
 *    {@link PoolableObjectFactory#validateObject} method.)  Objects that fail
 *    to validate will be dropped from the pool, and a different object will
 *    be borrowed. The default setting for this parameter is
 *    <code>false.</code>
 *  </li>
 *  <li>
 *    When {@link #setTestOnReturn <i>testOnReturn</i>} is set, the pool will
 *    attempt to validate each object before it is returned to the pool in the
 *    {@link #returnObject} method. (Using the provided factory's
 *    {@link PoolableObjectFactory#validateObject}
 *    method.)  Objects that fail to validate will be dropped from the pool.
 *    The default setting for this parameter is <code>false.</code>
 *  </li>
 * </ul>
 * <p>
 * Optionally, one may configure the pool to examine and possibly evict objects
 * as they sit idle in the pool and to ensure that a minimum number of idle
 * objects are available. This is performed by an "idle object eviction"
 * thread, which runs asynchronously. Caution should be used when configuring
 * this optional feature. Eviction runs contend with client threads for access
 * to objects in the pool, so if they run too frequently performance issues may
 * result. The idle object eviction thread may be configured using the following
 * attributes:
 * <ul>
 *  <li>
 *   {@link #setTimeBetweenEvictionRunsMillis <i>timeBetweenEvictionRunsMillis</i>}
 *   indicates how long the eviction thread should sleep before "runs" of examining
 *   idle objects.  When non-positive, no eviction thread will be launched. The
 *   default setting for this parameter is -1 (i.e., idle object eviction is
 *   disabled by default).
 *  </li>
 *  <li>
 *   {@link #setMinEvictableIdleTimeMillis <i>minEvictableIdleTimeMillis</i>}
 *   specifies the minimum amount of time that an object may sit idle in the pool
 *   before it is eligible for eviction due to idle time.  When non-positive, no object
 *   will be dropped from the pool due to idle time alone. This setting has no
 *   effect unless <code>timeBetweenEvictionRunsMillis > 0.</code> The default
 *   setting for this parameter is 30 minutes.
 *  </li>
 *  <li>
 *   {@link #setTestWhileIdle <i>testWhileIdle</i>} indicates whether or not idle
 *   objects should be validated using the factory's
 *   {@link PoolableObjectFactory#validateObject} method. Objects that fail to
 *   validate will be dropped from the pool. This setting has no effect unless
 *   <code>timeBetweenEvictionRunsMillis > 0.</code>  The default setting for
 *   this parameter is <code>false.</code>
 *  </li>
 *  <li>
 *   {@link #setSoftMinEvictableIdleTimeMillis <i>softMinEvictableIdleTimeMillis</i>}
 *   specifies the minimum amount of time an object may sit idle in the pool
 *   before it is eligible for eviction by the idle object evictor
 *   (if any), with the extra condition that at least "minIdle" object instances
 *   remain in the pool.  When non-positive, no objects will be evicted from the pool
 *   due to idle time alone. This setting has no effect unless
 *   <code>timeBetweenEvictionRunsMillis > 0.</code> and it is superceded by
 *   {@link #setMinEvictableIdleTimeMillis <i>minEvictableIdleTimeMillis</i>}
 *   (that is, if <code>minEvictableIdleTimeMillis</code> is positive, then
 *   <code>softMinEvictableIdleTimeMillis</code> is ignored). The default setting for
 *   this parameter is -1 (disabled).
 *  </li>
 *  <li>
 *   {@link #setNumTestsPerEvictionRun <i>numTestsPerEvictionRun</i>}
 *   determines the number of objects examined in each run of the idle object
 *   evictor. This setting has no effect unless
 *   <code>timeBetweenEvictionRunsMillis > 0.</code>  The default setting for
 *   this parameter is 3.
 *  </li>
 * </ul>
 * <p>
 * <p>
 * The pool can be configured to behave as a LIFO queue with respect to idle
 * objects - always returning the most recently used object from the pool,
 * or as a FIFO queue, where borrowObject always returns the oldest object
 * in the idle object pool.
 * <ul>
 *  <li>
 *   {@link #setLifo <i>lifo</i>}
 *   determines whether or not the pool returns idle objects in
 *   last-in-first-out order. The default setting for this parameter is
 *   <code>true.</code>
 *  </li>
 * </ul>
 * <p>
 * GenericObjectPool is not usable without a {@link PoolableObjectFactory}.  A
 * non-<code>null</code> factory must be provided either as a constructor argument
 * or via a call to {@link #setFactory} before the pool is used.
 * <p>

<think>首先,用户的问题是:“我想配置Spring Boot中Jedis的使用 请问如何在Spring Boot项目中配置和使用Jedis”。根据系统指令,我需要使用中文回答,结构清晰,逐步解决问题,并保证真实可靠。 参考了提供的引用: - 引用[1]:讲述了SpringBoot中Jedis配置,包括依赖导入和准备工作。 - 引用[2]:讨论了非Spring Boot项目中Jedis配置。 - 引用[3]:详细说明了Spring Boot整合Redis使用Jedis的步骤,包括依赖添加和配置文件。 用户的问题明确是关于Spring Boot的,所以我应该主要参考引用[1]和[3],因为它们更相关。 关键点: - 使用Jedis作为Redis客户端。 - 在Spring Boot项目中配置。 - 包括依赖添加、配置文件和基本使用。 结构回答: 1. **准备工作**:确保开发环境和Redis安装。 2. **添加依赖**:在pom.xml中添加必要的依赖。 3. **配置Redis属性**:在application.properties或application.yml中配置Redis连接信息。 4. **创建Jedis连接池**:配置JedisPool。 5. **使用Jedis**:在代码中注入JedisPool并使用Jedis实例进行操作。 6. **示例代码**:提供简单的代码示例。 7. **相关问题**:生成相关问题。 确保LaTeX格式: - 行内数学表达式用$...$,但我这里可能没有数学表达式,所以不需要。 - 独立公式用$$...$$,但这里也不涉及数学公式。 - 使用中文回答。 添加引用标识:在回答中引用相关内容时,在段落末尾自然地添加引用标识,如[^1]。 生成相关问题:在最后添加相关问题部分。 完整回答结构: - 开头简要介绍。 - 逐步配置步骤。 - 代码示例(使用代码块)。 - 相关问题。 相关问题示例: 1. 如何配置Redis连接池参数? 2. Jedis和Lettuce有什么区别? 3. 如何在Spring Boot中测试Jedis连接? 现在,构建回答:</think>### 如何在Spring Boot项目中配置和使用Jedis Jedis 是一个基于 Java 的 Redis 客户端库,用于高效操作 Redis 数据库。在 Spring Boot 中配置和使用 Jedis 可以简化 Redis 集成,以下是详细步骤(基于 Spring Boot 2.x 及以上版本)。整个过程分为准备工作、依赖添加、配置、代码实现三部分。 --- #### 1. **准备工作** 在开始前,确保满足以下条件: - **开发环境**:Java 1.8 或更高版本,Spring Boot 2.1.0.RELEASE 或更新版本(推荐使用 Spring Boot 3.x)。 - **Redis 安装**:已在本地或远程服务器安装并运行 Redis 服务。默认端口为 6379,可通过命令 `redis-server --version` 验证安装[^1]。 - **项目创建**:使用 Spring Initializr 创建 Spring Boot 项目(选择 Maven 或 Gradle)。 --- #### 2. **添加依赖** 在项目的 `pom.xml` 文件中添加 Jedis 和 Spring Data Redis 依赖。Jedis 是客户端库,而 Spring Data Redis 提供了与 Spring 生态的集成支持: ```xml <dependencies> <!-- Spring Data Redis 集成 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <!-- Jedis 客户端库 --> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>4.4.3</version> <!-- 推荐使用最新稳定版 --> </dependency> </dependencies> ``` - **说明**:`spring-boot-starter-data-redis` 默认可能使用 Lettuce 客户端,但添加 `jedis` 依赖后,Spring Boot 会自动切换为 Jedis(通过排除 Lettuce 依赖)[^1][^3]。 --- #### 3. **配置 Redis 连接** 在 `application.properties` 或 `application.yml` 文件中配置 Redis 连接信息。以下是 `application.properties` 示例: ```properties # Redis 服务器地址和端口 spring.redis.host=localhost spring.redis.port=6379 # 连接池配置(可选,优化性能) spring.redis.jedis.pool.max-active=10 spring.redis.jedis.pool.max-idle=5 spring.redis.jedis.pool.min-idle=1 spring.redis.jedis.pool.max-wait=2000ms # 最大等待时间 ``` - **关键点**: - `spring.redis.host` 和 `spring.redis.port` 是必需项,指向 Redis 服务器。 - 连接池参数(如 `max-active`)可防止资源耗尽,提升并发性能[^1][^3]。 - 如果 Redis 需要密码,添加 `spring.redis.password=your_password`。 --- #### 4. **代码实现:使用 Jedis 操作 Redis** Spring Boot 自动配置 Jedis 连接池(`JedisConnectionFactory`),可直接注入使用。以下是一个简单的服务类示例: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Service; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; @Service public class RedisService { // 注入 JedisPool(Spring Boot 自动创建) @Autowired private JedisPool jedisPool; // 示例1:设置和获取字符串值 public void setKey(String key, String value) { try (Jedis jedis = jedisPool.getResource()) { // 自动管理资源 jedis.set(key, value); } // try-with-resources 确保关闭连接 } public String getKey(String key) { try (Jedis jedis = jedisPool.getResource()) { return jedis.get(key); } } // 示例2:使用 Spring 的 StringRedisTemplate(更简化) @Autowired private StringRedisTemplate stringRedisTemplate; public void setWithTemplate(String key, String value) { stringRedisTemplate.opsForValue().set(key, value); } public String getWithTemplate(String key) { return stringRedisTemplate.opsForValue().get(key); } } ``` - **说明**: - **直接使用 Jedis**:通过 `JedisPool` 获取连接,执行 Redis 命令(如 `set`, `get`)。`try-with-resources` 确保连接自动关闭,避免泄漏。 - **使用 StringRedisTemplate**:Spring 提供的模板类封装了 Jedis 操作,更简洁且线程安全[^1][^3]。 - **测试**:在 Controller 中调用 `RedisService` 方法,启动应用后访问 Redis 验证数据。 --- #### 5. **验证和常见问题** - **启动应用**:运行 Spring Boot 主类,检查日志中是否有 Redis 连接成功消息(如 `JedisPool 初始化完成`)。 - **错误处理**: - 如果连接失败,检查 Redis 服务是否运行,或配置文件中 `host`/`port` 是否正确。 - 依赖冲突:确保无其他 Redis 客户端(如 Lettuce)干扰,可在 `pom.xml` 中排除 Lettuce: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> <exclusions> <exclusion> <groupId>io.lettuce</groupId> <artifactId>lettuce-core</artifactId> </exclusion> </exclusions> </dependency> ``` - **性能优化**:调整连接池参数(如 `max-active`)以适应高并发场景[^3]。 通过以上步骤,您可以在 Spring Boot 中高效配置和使用 Jedis。实际项目中,建议结合 Spring Cache 注解(如 `@Cacheable`)简化缓存逻辑。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值