Spring Boot中使用Redis一般有两种方式,一种是使用spring-data-redis,另一种是使用JedisPool
spring-data-redis方式
使用Maven构建的项目,在POM文件中添加如下依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
spring-data-redis使用RedisConnectionFactory这个工厂类来进行连接管理,代码中设置RedisConnectionFactory 相关的信息,一定要注意设置host、port、password,否则将会出现很多奇怪的问题,比如:
- (error) NOAUTH Authentication required
- Cannot get Jedis connection; nested exception is redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resource from the pool
@Bean
public RedisConnectionFactory redisCF() throws DViewException {
JedisConnectionFactory factory = new JedisConnectionFactory();
factory.setHostName(host);
factory.setPort(port);
factory.setPassword(password);
factory.setUsePool(true);
return factory;
}
然后再需要的地方使用spring注入RedisTemplate即可,其中T是泛型,代表你的业务对象
@Autowired
private RedisTemplate<String, T> redisTemplate;
JedisPool
使用Maven构建的项目,在POM文件中添加如下依赖:
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
JedisPool使用池来管理连接,可以通过该池对象获取jedis的连接,代码中设置JedisPool相关的信息
@Bean
public JedisPool redisPoolFactory() {
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
jedisPoolConfig.setMaxIdle(maxIdle);
jedisPoolConfig.setMinIdle(minIdle);
jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout, password);
return jedisPool;
}
然后在代码中需要的地方使用spring注入JedisPool即可
@Autowired
private JedisPool jedisPool;
相关的Redis配置可以在配置文件application.properties中指定
spring.redis.database=0
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=admin
spring.redis.pool.max-active=8
spring.redis.pool.max-wait=-1
spring.redis.pool.max-idle=8
spring.redis.pool.min-idle=0
spring.redis.timeout=1000
Spring Boot中使用Redis,利用spring-data-redis和JedisPool来和Redis进行交互还是比较简单的,一般步骤为对JedisConnectionFactory或者JedisPool 进行配置,然后获取RedisTemplate或者Jedis进行使用