基于Java语言演示Redis Client的简单使用:
1、引入Maven依赖:
<dependency> <groupId>redis.clients</> <artifactId>jedis</> <version>2.9.0</> <type>jar</> <scope>complie</> </>
2、生成Jedis对象:
Jedis jedis = new Jedis(String host,int port,int connectionTimeout,int soTimeout); 参数列表: host:Redis节点所在机器ip port:Redis节点端口 connectionTimeout:客户端连接超时 soTimeout:客户端读写超时 执行set/get演示 jedis.set("hello","world"); String value = jedis.get("hello");
Jedis直连示意图:
1、生成Jedis对象 2、Jedis执行命令 3、返回执行结果 4、关闭Jedis连接
Jedis连接池示意图:
1、从资源池借Jedis对象 2、Jidis执行命令 3、返回执行结果 4、归还Jedis对象给连接池
连接池简单使用:
扫描二维码关注公众号,回复:
7376957 查看本文章
GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig(); JedisPool jedisPool = new JedisPool(poolConfig,host,port); Jedis jedis = null; try{ jedis = jedisPool.getResource(); jedis.set("hello","world"); } catch(Exception e){ ... }finally{ if(jedis != null){ jedis.close(); } }
连接池与直连对比:
优点:
---直连:简单方便、适用于少量长期连接场景
---连接池:Jedis预先生成,降低开销使用、连接池的形式保护和控制资源的使用
缺点:
---直连:存在每次新建/关闭TCP开销、资源无法控制,存在连接泄露的可能、Jedis对象线程不安全
---连接池:相对直连使用麻烦,在资源管理上需要更多得参数来保证