Jedis介绍
- (1)什么是Jedis?
操作Redis的工具类:Jedis
》》Redis:数据库的名字
》》Jedis:工具类的名字
Jedis同样也是托管在github上,地址: https://github.com/xetorthio/jedis。 - (2)如何搭建Jedis?
使用Jedis操作redis需要导入jar包如下
Jedis的操作
- (1)Jedis如何使用?
操作步骤:
》》1:创建一个Jedis对象
》》 2:执行Redis指令
//1:创建Jedis对象
Jedis jedis = new Jedis("localhost", 6379);
//2:调用方法执行Redis指令(每一条指令,都有一个方法)
jedis.set("name", "wzx");
jedis.sadd("mylist","aaa","bbb","ccc");
String addr = jedis.get("addr");
System.out.println("addr:"+addr);
Jdbc连接池原理
- (1)什么时候接触连接池?
Jdbc连接池 - (2)连接池原理
频繁创建与销毁链接比较消耗性能
创建集合初始化多个Connection
需要时调getConnection()申请
使用完时调用close()放回 - (3)连接池的意义
重用连接,提高性能
Jedis连接池基本实现1
-
(1)Jedis连接池原理
基本类似
-
(2)代码实现步骤
1:创建连接池的配置对象
2:创建连接池
3:从连接池中获取一个连接
4:执行Redis执行 Map<String,String> set get
5:释放连接
//1:创建连接池的配置对象
JedisPoolConfig config = new JedisPoolConfig();
//1.1 设置最大连接数
config.setMaxTotal(30);
//1.2 设置空闲连接数
config.setMaxIdle(10);
//2:创建连接池
JedisPool pool = new JedisPool(config, "localhost", 6379);
//3:从连接池中获取一个连接
Jedis jedis = pool.getResource();
//4:执行Redis执行
jedis.set("email", "[email protected]");
//5:释放连接
jedis.close();
Jedis连接池基本实现1
- (1)硬编码
配置参数写在java代码,编译成class,将来必须修改java代码才能改配置
项目中,使用配置文件来配置参数 - (2)改成工具类加配置文件
src\com.wzx.pack01_redis\Demo3JedisPool.java
public class Demo3JedisPool {
@Test
public void test01() {
Jedis jedis = JedisUtils.getJedis();//调用静态方法
jedis.set("xxx", "yyyyy");
jedis.close();
}
}
src\jedis.properties
- properites文件配置参数,然后再由程序读进这些配置参数给对象使用,这是JAVAEE经常采用的方式
maxTotal=30
maxIdle=10
url=localhost
port=6379
src\com.wzx.pack01_redis\JedisUtils.java
读.properties文件,可以先使用类加载器去加载成流,再使用Properties类来读。
也可以使用ResourceBundle
读.propties
public class JedisUtils {
private static JedisPool pool = null;
//1:创建一个连接池
static{
//1.1 解析properties文件
ResourceBundle bundle = ResourceBundle.getBundle("jedis");
//获取参数
String maxTotal = bundle.getString("maxTotal");
String maxIdle = bundle.getString("maxIdle");
String url = bundle.getString("url");
String port = bundle.getString("port");
//1.2创建连接池
//1:创建连接池的配置对象
JedisPoolConfig config = new JedisPoolConfig();
//1.1 设置最大连接数
config.setMaxTotal(Integer.parseInt(maxTotal));
//1.2 设置空闲连接数
config.setMaxIdle(Integer.parseInt(maxIdle));
//2:创建连接池
pool = new JedisPool(config, url, Integer.parseInt(port));
}
//2:对外提供一个获取连接的方法
public static Jedis getJedis(){
return pool.getResource();
}
//3:提供释放资源的方法
public static void close(Jedis jedis){
if(jedis != null) {
jedis.close();
}
}
}