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. 通过分析 JDK 源代码研究 TreeMap 红黑树算法实

    TreeMap和TreeSet是Java Collection Framework的两个重要成员,其中TreeMap是Map接口的常用实现类,而TreeSet是Set接口的常用实现类.虽然HashMa ...

  2. Hibernate 核心接口和工作机制

    主要内容 Configuration类 sessionFactory接口 session接口 Transaction接口 Query 和 criteria接口 1.Configuration类 负责管 ...

  3. Gulp文档入门的文档

    Gulp自动化执行文件的操作 首先gulp基于node开发的,先按照node.js,使用npm sudo npm install -g gulp (在全局的范围安装 gulp) gulp --help ...

  4. 关于Dubbo一个接口多个实现的解决方案

    如题,其实这个问题在官方文档中已经说明了.我直接贴图就好了 更多学习请参考:minglisoft.cn/technology

  5. 最简单 iText 的 PDF 生成方案(含中文解决方案)HTML 转为 PDF

    转自:http://my.oschina.net/sanji/blog/277704 最近正好项目有用到 ITEXT ,在网络上搜索了一番,发现了很多方案,但是感觉对于一般开发来说都太复杂了,本文提供 ...

  6. 开涛spring3(5.3) - Spring表达式语言 之 5.3 SpEL语法

    5.3  SpEL语法 5.3.1  基本表达式 一.字面量表达式: SpEL支持的字面量包括:字符串.数字类型(int.long.float.double).布尔类型.null类型. 类型 示例 字 ...

  7. 四、 添加模型Model(ASP.NET MVC5 系列)

    在这一章节中我们将添加一些classes类来管理数据库中的movies.这些classes类就是ASP.NET MVC应用程序中的"model". 我们将用.NET框架中的数据访问 ...

  8. Swift 入门之简单语法(五)

    面向对象 目标 构造函数 构造函数的基本概念 构造函数的执行顺序 KVC 在构造函数中的使用及原理 便利构造函数 析构函数 区分 重载 和 重写 懒加载 只读属性(计算型属性) 设置模型数据(didS ...

  9. CentOS7使用rpm包安装MySQL

    说明 本文写于2017-05-20,使用MySQL-5.7.18.操作系统为64位CentOS Linux release 7.2.1511 (Core),以桌面形式安装. 卸载MariaDB Cen ...

  10. Ubuntu安装genymotion模拟器步骤

    1.安装VitrualBox genymotion模拟器需要有VirtualBox环境,打开终端(ctrl + alt + T),执行以下命令: sudo apt-get install virtua ...