连接池参数,正式环境配置在yml文件中

package cn.com.suntree.utils.myself;

import lombok.extern.log4j.Log4j2;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

@Configuration
@EnableCaching
@Log4j2
public class RedisCacheConfiguration extends CachingConfigurerSupport {


//@Value("${spring.redis.host}")
private String host = "127.0.0.1";

//@Value("${spring.redis.port}")
private int port = 6379;

private int timeout = 10;

//@Value("${spring.redis.pool.max-idle}")
private int maxIdle = 8;//最大能够保持idle的数量,控制一个pool最多有多少个状态为idle的jedis实例

// @Value("${spring.redis.pool.max-wait}")
private long maxWaitMillis = -1;//getBlockWhenExhausted为true时,连接会阻塞,超过了阻塞的时间(设定的maxWaitMillis,单位毫秒)时会报错

private int maxTotal = 100;//在指定时刻通过pool能够获取到的最大的连接的jedis个数

// @Value("${spring.redis.password}")
private String password = "yourpw";

@Bean
public JedisPool redisPoolFactory() {
log.info("JedisPool注入成功!!");
log.info("redis地址:" + host + ":" + port);
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
jedisPoolConfig.setMaxIdle(maxIdle);
jedisPoolConfig.setMaxTotal(maxTotal);
jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
jedisPoolConfig.setMinEvictableIdleTimeMillis(100);//逐出连接的最小空闲时间 默认1800000毫秒(30分钟)
jedisPoolConfig.setTimeBetweenEvictionRunsMillis(200); //逐出扫描的时间间隔(毫秒) 如果为负数,则不运行逐出线程, 默认-1
JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout, password);

return jedisPool;
}

}

获取连接

@Component
public class JedisUtils {

@Autowired
JedisPool jedisPool;
public Jedis getJedis() {
return jedisPool.getResource();
}

运用,一定要关闭!!!

Jedis jedis = null;
try {
jedis = jedisUtils.getJedis();
jedis.set(remind.getRemindTm(), JSON.toJSONString(remind));
} finally {
if (jedis != null) {
jedis.close();
}
}