认识jedis
jedis 是redis官方推荐的的Java连接redis工具【jedis命令和redis命令一致】
依赖
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>4.1.1</version>
</dependency>
依赖和Jar包可以去此网站查询:
https://mvnrepository.com/
连接和使用:
Jedis jedis = new Jedis("127.0.0.1", 6379);//指定Redis服务Host和port个端口
jedis.auth("123456"); //如果Redis服务连接需要密码,制定密码
System.out.println("jedis.ping():"+jedis.ping());
jedis.set("a1","南京");
System.out.println(jedis.get("a1"));
jedis.close();//关闭连接
Jedis基本使用十分简单,在每次使用时,构建Jedis对象即可。在Jedis对象构建好之后,Jedis底层会打开一条Socket通道和Redis服务进行连接。所以在使用完Jedis对象之后,需要调用Jedis.close()方法把连接关闭,不如会占用系统资源。当然,如果应用非常平凡的创建和销毁Jedis对象,对应用的性能是很大影响的,因为构建Socket的通道是很耗时的(类似数据库连接)。我们应该使用连接池来减少Socket对象的创建和销毁过程。
连接池的使用
Jedis连接池是基于apache-commons pool2实现的。在构建连接池对象的时候,需要提供池对象的配置对象,及JedisPoolConfig(继承自GenericObjectPoolConfig)。我们可以通过这个配置对象对连接池进行相关参数的配置(如最大连接数,最大空数等)。
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxIdle(8);
config.setMaxTotal(18);
JedisPool pool = new JedisPool(config, "127.0.0.1", 6379, 2000, "password");
Jedis jedis = pool.getResource();
String value = jedis.get("key");
......
jedis.close();
pool.close();
使用Jedis连接池之后,在每次用完连接对象后一定要记得把连接归还给连接池。Jedis对close方法进行了改造,如果是连接池中的连接对象,调用Close方法将会是把连接对象返回到对象池,若不是则关闭连接。可以查看如下代码
@Override
public void close() { //Jedis的close方法
if (dataSource != null) {
if (client.isBroken()) {
this.dataSource.returnBrokenResource(this);
} else {
this.dataSource.returnResource(this);
}
} else {
client.close();
}
}
//另外从对象池中获取Jedis链接时,将会对dataSource进行设置
// JedisPool.getResource()方法
public Jedis getResource() {
Jedis jedis = super.getResource();
jedis.setDataSource(this);
return jedis;
}
或者直接使用无参构造
JedisPool jedisPool = new JedisPool();//无参构造时,默认参数是127.0.0.1,6379
Jedis jedis = jedisPool.getResource();
jedis.auth("123456"); //如果Redis服务连接需要密码,制定密码
System.out.println("jedis.ping():"+jedis.ping());
jedis.set("a1","南京");
System.out.println(jedis.get("a1"));
jedis.close();//关闭连接
本文原创内容较少,大家可参考链接
来源链接:https://www.jianshu.com/p/a1038eed6d44