1新增依赖
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.gc</groupId>
<artifactId>redisDemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-pool2 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.4.2</version>
</dependency>
</dependencies>
</project>
由于使用的是jedis2.9 在使用jedisPool选择的是第三个构造jedisPool的方法
public JedisPool() {
this(Protocol.DEFAULT_HOST, Protocol.DEFAULT_PORT);
}
public JedisPool(final GenericObjectPoolConfig poolConfig, final String host) {
this(poolConfig, host, Protocol.DEFAULT_PORT, Protocol.DEFAULT_TIMEOUT, null,
Protocol.DEFAULT_DATABASE, null);
}
public JedisPool(String host, int port) {
this(new GenericObjectPoolConfig(), host, port, Protocol.DEFAULT_TIMEOUT, null,
Protocol.DEFAULT_DATABASE, null);
}
GenericObjectPoolConfig 中配置了默认的config信息 ,使用此方法初始化一个jedisPool连接池
package redisDemo;
import org.junit.Test;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
/**
* redis连接池
* @Description: TODO(用一句话描述该文件做什么)
* @author gc
* @date 2018年10月2日
*
*/
public class RedisPool {
public Jedis getJedis(){
JedisPool jedisPool = new JedisPool("192.168.34.3",6379);
Jedis jedis=null;
try{
jedis =jedisPool.getResource();
jedis.auth("root");
}catch (Exception e){
e.printStackTrace();
}finally {
if(jedisPool!=null){
jedisPool.close();
}
}
return jedis;
}
@Test
public void testJedis(){
Jedis jedis = getJedis();
String username = jedis.get("username");
System.out.println(username);
jedis.close();
}
}
完成连接池的初步创建 在2.9版本中继承GenericObjectPoolConfig
package redis.clients.jedis;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
public class JedisPoolConfig extends GenericObjectPoolConfig {
public JedisPoolConfig() {
// defaults to make your life with connection pool easier :)
setTestWhileIdle(true);
setMinEvictableIdleTimeMillis(60000);
setTimeBetweenEvictionRunsMillis(30000);
setNumTestsPerEvictionRun(-1);
}
}
故使用默认的连接池配置