Jedis使用
概述:
Jedis是Redis官方推荐的Java连接开发工具。要在Java开发中使用好Redis中间件,必须对Jedis熟悉才能写成漂亮的代码。这篇文章不描述怎么安装Redis和Reids的命令,只对Jedis的使用进行对介绍。
1. 基本使用
Jedis的基本使用非常简单,只需要创建Jedis对象的时候指定host,port, password即可。当然,Jedis对象又很多构造方法,都大同小异,只是对应和Redis连接的socket的参数不一样而已。
Jedis jedis = new Jedis("localhost", 6379); //指定Redis服务Host和port jedis.auth("xxxx"); //如果Redis服务连接需要密码,制定密码 String value = jedis.get("key"); //访问Redis服务 jedis.close(); //使用完关闭连接
Jedis基本使用十分简单,在每次使用时,构建Jedis对象即可。在Jedis对象构建好之后,Jedis底层会打开一条Socket通道和Redis服务进行连接。所以在使用完Jedis对象之后,需要调用Jedis.close()方法把连接关闭,不如会占用系统资源。当然,如果应用非常平凡的创建和销毁Jedis对象,对应用的性能是很大影响的,因为构建Socket的通道是很耗时的(类似数据库连接)。我们应该使用连接池来减少Socket对象的创建和销毁过程。
2. 连接池使用
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; }
3.Jedis简易工具类
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); }
封装连接参数
创建jedis的配置文件:jedis.properties
jedis.host=192.168.40.130 jedis.port=6379 jedis.maxTotal=50 jedis.maxIdle=10
加载配置信息
创建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")); 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); } }
获取连接
对外访问接口,提供jedis连接对象,连接从连接池获取,在JedisUtils中添加一个获取jedis的方法:getJedis
public static Jedis getJedis(){ Jedis jedis = jedisPool.getResource(); return jedis; }
作者:曹金桂
链接:https://www.jianshu.com/p/a1038eed6d44
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

浙公网安备 33010602011771号