連接池參數,正式環境配置在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();
}
}