一:引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
二:配置文件
redis:
host: 127.0.0.1
port: 6379
password:
# Redis数据库索引(默认为0)
database: 0
# 连接超时时间(毫秒)
timeout: 10000
#连接耗尽时是否阻塞, false报异常,ture阻塞直到超时, 默认true
block-when-exhausted: true
pool:
# 连接池中的最大空闲连接
max-idle: 20
# 连接池中的最小空闲连接
min-idle: 5
# 连接池最大连接数(使用负值表示没有限制)
max-active: 20
# 连接池最大阻塞等待时间(使用负值表示没有限制)
max-wait: 10000
三:依赖注入到Spring容器,注意没有redis有密码和没密码时配置连接池是有区别的,代码中有注释
package com.ly.provider.config.redis;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
/**
* Created by liyu on 2018/4/27.
*/
@Configuration
@EnableAutoConfiguration
public class RedisConfiguration {
@Value("${redis.host}")
private String host;
@Value("${redis.port}")
private int port;
@Value("${redis.timeout}")
private int timeout;
@Value("${redis.pool.max-idle}")
private int maxIdle;
@Value("${redis.pool.max-wait}")
private long maxWaitMillis;
@Value("${redis.password}")
private String password;
@Value("${redis.block-when-exhausted}")
private boolean blockWhenExhausted;
@Bean
public JedisPool redisPoolFactory() throws Exception{
System.out.println("=============JedisPool注入成功!!redis地址:" + host + ":" + port);
System.out.println("=============JedisPool注入成功!!password:" + password + "maxIdle:" + maxIdle+ "max-wait:" + maxWaitMillis+ "blockWhenExhausted:" + blockWhenExhausted);
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
jedisPoolConfig.setMaxIdle(maxIdle);
jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
// 连接耗尽时是否阻塞, false报异常,ture阻塞直到超时, 默认true
jedisPoolConfig.setBlockWhenExhausted(blockWhenExhausted);
// 是否启用pool的jmx管理功能, 默认true
jedisPoolConfig.setJmxEnabled(true);
//redis设置了密码时使用,没密码使用该方式初始化连接池会失败
//JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout,password);
//redis没设置密码时使用
JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout);
return jedisPool;
}
}