连接以及关闭redis客户端
后续测试都需要用到Redis连接,所以,我们先创建一个JedisPool,用于获取Redis连接
实现步骤:
1.创建JedisPoolConfig配置对象,指定最大空闲连接为10个、最大等待时间为3000毫秒、最大连接数为50、最小空闲连接为5个。
2.创建JedisPool
3.编写测试用例,查看Redis中所有的key
a)从Redis连接池获取Redis连接
b)调用keys方法获取所有的key
c)遍历打印所有的key
代码编写
建立Maven工程,导入依赖
pom.xml
<dependencies>
<!--redis的Java客户端-->
<dependency>
<groupId>redis.clients</groupId>
<!--jedis是redis提供给Java开发的一套库-->
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
<!--单元测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.14.3</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
RedisTest.java
package xiaoliuxxs.myredis.api_test;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import java.util.Set;
public class RedisTest {
private JedisPool jedisPool;
@BeforeTest
public void beforeTest(){
//创建JedisPoolConfig配置对象
JedisPoolConfig config = new JedisPoolConfig();
//指定最大空闲连接为10个
config.setMaxIdle(10);
//最小空闲连接为5个
config.setMinIdle(5);
//最大等待时间为3000毫秒
config.setMaxWaitMillis(3000);
//最大连接数为50
config.setMaxTotal(50);
//jedisPool = new JedisPool(config, "hadoop",6379);
jedisPool = new JedisPool(config, "hadoop");
}
@Test
public void keysTest(){
//从Redis连接池获取Redis连接
Jedis jedis = jedisPool.getResource();
//调用keys方法获取所有的key
Set<String> keySet = jedis.keys("*");
for (String key : keySet) {
System.out.println(key);
}
}
@AfterTest
public void afterTest(){
//关闭连接池
jedisPool.close();
}
}
在命令行输入keys *查看一下
小结:
操作Redis一般使用连接池,这样可以有效复用资源