1、导入相关jar包
2、基于连接池获取连接
- JedisPool:Jedis提供的连接池技术
- poolConfig:连接池配置对象
- host:redis服务地址
- port:redis服务端口号
JedisPool的构造器如下:
public JedisPool(GenericObjectPoolConfig poolConfig, String host, int port) {
this(poolConfig, host, port, 2000, (String)null, 0, (String)null);
}
3、封装连接参数
创建jedis的配置文件:jedis.properties
jedis.host=192.168.40.130
jedis.port=6379
jedis.maxTotal=50
jedis.maxIdle=10
4、加载配置信息获取连接
创建JedisUtils:com.itheima.util.JedisUtils,使用静态代码块初始化资源
public class JedisUtils {
private static int maxTotal;
private static int maxIdel;
private static String host;
private static int port;
private static JedisPoolConfig jpc;
private static JedisPool jp;
static {
ResourceBundle bundle = ResourceBundle.getBundle("redis");
// 最大连接数
maxTotal = Integer.parseInt(bundle.getString("redis.maxTotal"));
// 默认连接数
maxIdel = Integer.parseInt(bundle.getString("redis.maxIdel"));
// ip地址
host = bundle.getString("redis.host");
// 端口号
port = Integer.parseInt(bundle.getString("redis.port"));
//Jedis连接池配置
jpc = new JedisPoolConfig();
jpc.setMaxTotal(maxTotal);
jpc.setMaxIdle(maxIdel);
jp = new JedisPool(jpc,host,port);
}
public static Jedis getJedis(){
// 连接池对象
Jedis jedis = jedisPool.getResource();
return jedis;
}
}
5、测试代码
import com.util.JedisUtils;
import redis.clients.jedis.Jedis;
import java.util.ResourceBundle;
public class JedisTest {
public static void main(String[] args) {
Jedis jedis = JedisUtils.getJedis();
jedis.set("name","Tom");
String name= jedis.get("name");
System.out.println(name);
jedis.close();
}
}