一.导包
<!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
二.开始测试
@Test
public void testName() throws Exception {
JedisPoolConfig poolConfig = new JedisPoolConfig();
// 最大连接数
poolConfig.setMaxTotal(50);
//最大空闲连接
poolConfig.setMaxIdle(10);
//最小空闲连接
poolConfig.setMinIdle(5);
poolConfig.setTestOnCreate(true); //创建连接的时候需要先进行测试连接是否可用
poolConfig.setTestOnReturn(true);//返还连接的时候需要先测试
//连接超时
poolConfig.setMaxWaitMillis(1);
//获取连接池
JedisPool jedisPool=new JedisPool(poolConfig, "192.168.89.250", 6379, 3000);
//获得连接
Jedis jedis = jedisPool.getResource();
//在redis中设置参数
jedis.set("mykey", "hello1");
//在redis中获取参数
String string = jedis.get("setkey");
System.out.println(string);
//记得关闭
jedis.close();
}
三.封装到before中
Jedis jedis;
@Before
public void testName1() throws Exception {
JedisPoolConfig poolConfig = new JedisPoolConfig();
// 最大连接数
poolConfig.setMaxTotal(50);//最大空闲连接poolConfig.setMaxIdle(10);//最小空闲连接poolConfig.setMinIdle(5);poolConfig.setTestOnCreate(true); //创建连接的时候需要先进行测试连接是否可用poolConfig.setTestOnReturn(true);//返还连接的时候需要先测试//连接超时poolConfig.setMaxWaitMillis(1);//获取连接池JedisPool jedisPool=new JedisPool(poolConfig, "192.168.89.250", 6379, 3000);//获得连接jedis = jedisPool.getResource();}四.封装到工具类中,调用工具类获取连接(☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆)
package cn.itcast.spider.uitl;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
public class JedisUtil {
private static JedisPool jedisPool;
public static JedisPool getjedispool() {
if (null == jedisPool) {
// 数据库连接池配置信息
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxTotal(50);
poolConfig.setMaxIdle(10);
poolConfig.setMinIdle(5);
poolConfig.setTestOnCreate(true); // 创建连接的时候需要先进行测试连接是否可用
poolConfig.setTestOnReturn(true);// 返还连接的时候需要先测试
poolConfig.setMaxWaitMillis(1);
// 获得连接redis的连接池的连接
jedisPool = new JedisPool(poolConfig, "192.168.89.250", 6379, 3000);
return jedisPool;
} else {
// 如果连接不为空,就使用原来的连接;
return jedisPool;
}
}
// 从连接池里面获取一个连接
public static Jedis getjedis() {
JedisPool getjedispool = getjedispool();
Jedis jedis = getjedispool.getResource();
return jedis;
}
}