Basic usage example

using Jedis in a multithreaded environment

You shouldn't use the same instance from different threads because you'll have strange errors. And sometimes creating lots of Jedis instances is not good enough because it means lots of sockets and connections, which leads to strange errors as well. A single Jedis instance is not threadsafe!To avoid these problems, you should use JedisPool, which is a threadsafe pool of network connections. You can use the pool to reliably create several Jedis instances, given you return the Jedis instance to the pool when done. This way you can overcome those strange errors and achieve great performance.

To use it, init a pool:

JedisPool pool = new JedisPool(new JedisPoolConfig(), "localhost");

You can store the pool somewhere statically, it is thread-safe.

JedisPoolConfig includes a number of helpful Redis-specific connection pooling defaults. JedisPool is based on Commons Pool 2, so you may want to have a look at Commons Pool's configuration. Please see http://commons.apache.org/proper/commons-pool/apidocs/org/apache/commons/pool2/impl/GenericObjectPoolConfig.html for more details.

You use it by:

/// Jedis implements Closable. Hence, the jedis instance will be auto-closed after the last statement.
try (Jedis jedis = pool.getResource()) {
/// ... do stuff here ... for example
jedis.set("foo", "bar");
String foobar = jedis.get("foo");
jedis.zadd("sose", 0, "car"); jedis.zadd("sose", 0, "bike");
Set<String> sose = jedis.zrange("sose", 0, -1);
}
/// ... when closing your application:
pool.destroy();

If you can't use try-with-resource, you can still enjoy with Jedis.close().

Jedis jedis = null;
try {
jedis = pool.getResource();
/// ... do stuff here ... for example
jedis.set("foo", "bar");
String foobar = jedis.get("foo");
jedis.zadd("sose", 0, "car"); jedis.zadd("sose", 0, "bike");
Set<String> sose = jedis.zrange("sose", 0, -1);
} finally {
if (jedis != null) {
jedis.close();
}
}
/// ... when closing your application:
pool.destroy();

If Jedis was borrowed from pool, it will be returned to pool with proper method since it already determines there was JedisConnectionException occurred. If Jedis wasn't borrowed from pool, it will be disconnected and closed.

使用实例:

package com.scut.emos.nziot_base.redis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
/**
* Created by CMQ on 2017/3/9.
*/
public class JedisPoolHelper {
private static JedisPool pool = null;
public static JedisPool getPool(JedisPoolConfig config,String host,int port) {
if (pool == null) {
pool = new JedisPool(config, host, port);
}
return pool;
}
public void destroyPool(){
pool.destroy();
}
}
package com.scut.emos.nziot_base;
import com.scut.emos.nziot_base.redis.JedisPoolHelper;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
/**
* 测试类
*/
public class TestClass {
private static JedisPool pool = null;
public TestClass(){
pool = JedisPoolHelper.getPool(getConfig(),"222.201.145.215",6379);
}
public static JedisPoolConfig getConfig(){
JedisPoolConfig config = new JedisPoolConfig();
//控制一个pool可分配多少个jedis实例,通过pool.getResource()来获取;
//如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。
config.setMaxTotal(500);
//控制一个pool最多有多少个状态为idle(空闲的)的jedis实例。
config.setMaxIdle(5);
//表示当borrow(引入)一个jedis实例时,最大的等待时间,如果超过等待时间,则直接抛出JedisConnectionException;
config.setMaxWaitMillis(1000 * 100);
//在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的;
config.setTestOnBorrow(true);
return config;
}
public void sampleUseJedis(){
Jedis jedis = null;
try {
jedis = pool.getResource();
jedis.set("cdaf","dashuaiguola");
String str = jedis.get("cai");
} finally {
if (jedis != null) {
jedis.close();
}
}
}
public static void main(String args[]){ new TestClass().sampleUseJedis();
// 1. create log
Logger log = Logger.getLogger(TestClass.class);
// 2. get log config file
PropertyConfigurator.configure("log4j.properties");
// 3. start log
log.info("sdfa"); }
}

6.如何使用jedis的线程池的更多相关文章

  1. jedis使用线程池封装redis基本操作

    redisclient jedis 经常使用的 操作 key value hash list set zset 的基本操作 package cn.zto.util; import java.util. ...

  2. 基于线程池的多线程售票demo2.0(原创)

    继上回基于线程池的多线程售票demo,具体链接: http://www.cnblogs.com/xifenglou/p/8807323.html以上算是单机版的实现,特别使用了redis 实现分布式锁 ...

  3. 关于Jedis是否线程安全的测试

    转: 关于Jedis是否线程安全的测试 2018年09月20日 15:53:51 cwz_茶仔 阅读数:659   版权声明:转载请注明出处 https://blog.csdn.net/jk94043 ...

  4. 多线程爬坑之路-学习多线程需要来了解哪些东西?(concurrent并发包的数据结构和线程池,Locks锁,Atomic原子类)

    前言:刚学习了一段机器学习,最近需要重构一个java项目,又赶过来看java.大多是线程代码,没办法,那时候总觉得多线程是个很难的部分很少用到,所以一直没下决定去啃,那些年留下的坑,总是得自己跳进去填 ...

  5. C#多线程之线程池篇3

    在上一篇C#多线程之线程池篇2中,我们主要学习了线程池和并行度以及如何实现取消选项的相关知识.在这一篇中,我们主要学习如何使用等待句柄和超时.使用计时器和使用BackgroundWorker组件的相关 ...

  6. C#多线程之线程池篇2

    在上一篇C#多线程之线程池篇1中,我们主要学习了如何在线程池中调用委托以及如何在线程池中执行异步操作,在这篇中,我们将学习线程池和并行度.实现取消选项的相关知识. 三.线程池和并行度 在这一小节中,我 ...

  7. C#多线程之线程池篇1

    在C#多线程之线程池篇中,我们将学习多线程访问共享资源的一些通用的技术,我们将学习到以下知识点: 在线程池中调用委托 在线程池中执行异步操作 线程池和并行度 实现取消选项 使用等待句柄和超时 使用计时 ...

  8. NGINX引入线程池 性能提升9倍

    1. 引言 正如我们所知,NGINX采用了异步.事件驱动的方法来处理连接.这种处理方式无需(像使用传统架构的服务器一样)为每个请求创建额外的专用进程或者线程,而是在一个工作进程中处理多个连接和请求.为 ...

  9. Java线程池解析

    Java的一大优势是能完成多线程任务,对线程的封装和调度非常好,那么它又是如何实现的呢? jdk的包下和线程相关类的类图. 从上面可以看出Java的线程池主的实现类主要有两个类ThreadPoolEx ...

随机推荐

  1. iOS开发之判断用户是否打开APP通知开关

    一.前言 在多数移动应用中任何时候都只能有一个应用程序处于活跃状态,如果其他应用此刻发生了一些用户感兴趣的那么通过通知机制就可以告诉用户此时发生的事情.iOS中通知机制又叫消息机制,其包括两类:一类是 ...

  2. 安装mongodb后启动报错libstdc++

    安装mongo后启动报错如下图 显然说是libstdc++.so文件版本的问题,这种一般都是gcc版本太低了 接着查询gcc的版本    strings /usr/lib/libstdc++.so.6 ...

  3. 如何搭建易企秀H5平台?

    导读 易企秀如何开启伪静态支持? 一秀如何开启伪静态? 下载易企秀源码 oschina: http://git.oschina.net/jsper/html5Editor Windows下搭建环境 安 ...

  4. 《JavaScript高级程序设计》里对 call() 和 apply() 的解释 (116页)

    每个函数都包含两个非继承而来的方法:apply()和call().这两个方法的用途都是在特定的作用域中调用函数,实际上等于设置函数体内this对象的值. apply(): 方法接受两个参数:一个是在其 ...

  5. Java UDP Socket

    本文转载地址:          Java学习路上的收获:http://blog.csdn.net/qinpeng100423/article/details/8980423 一. UDP协议定义 U ...

  6. 2-LPC1778之GPIO

    其实这篇文章主要是介绍自己为其写的GPIO库,自己借鉴了原子写的STM32,野火写的K60,还有LPC官方库,然后按照自己平时用的,然后写了一个..其实写库的主要目的是为了方便(主要是方便操作)以后自 ...

  7. iOS textfield 限制输入字数长度

    iOS textfield限制输入的最大长度 [self.textFiled addTarget:self action:@selector(textFieldDidChange:) forContr ...

  8. CefSharp使用入门

    首先这是很重要的,环境搭建: 我用的是VS2017 步骤            方法 1.            打开VS的安装管理器 2.             进入修改界面,使用C++的桌面开发 ...

  9. UNIX文件I/O

    第一次用markdown语法写博客,写出来的还比较整齐,感觉博客园对序号的支持不是很好,调了一会才有了比较满意的效果,还有有哪位知道使用markdown如何插入frame? 这边博客主要说了APUE中 ...

  10. 快速找到ARP病毒源

    第一招:使用Sniffer抓包 在网络内任意一台主机上运行抓包软件,捕获所有到达本机的数据包.如果发现有某个IP不断发送请求包,那么这台电脑一般就是病毒源.原理:无论何种ARP病毒变种,行为方式有两种 ...