Chinaunix首页 | 论坛 | 博客
  • 博客访问: 94234
  • 博文数量: 25
  • 博客积分: 10
  • 博客等级: 民兵
  • 技术积分: 316
  • 用 户 组: 普通用户
  • 注册时间: 2012-08-02 00:39
文章分类

全部博文(25)

文章存档

2013年(25)

我的朋友

分类: 架构设计与优化

2013-04-22 17:00:16

import java.util.*;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class JedisPoolClient {


    private static JedisPoolConfig config = null;
    private static JedisPool pool = null;  
    private static Jedis jedis  = null;


    public static void main(String[] args) throws Exception {

        JedisPoolClient client = new JedisPoolClient();
        try {        
            client.doit();
        } catch (Exception e){
        } finally {
            try {
                client.destroy();
            } catch (Exception e){
            }
        }
    }
    
    //主逻辑,多线程使用线程池连接取值
    public void doit() throws Exception{
        _init();
        _testThread();
    }

    //初始化连接池配置参数
    private void _init() throws Exception{
        config = new JedisPoolConfig();
        config.setMaxActive(100);
        config.setMaxIdle(20);
        config.setMaxWait(1000);
        config.setTestOnBorrow(true);

        pool = new JedisPool(config,"localhost");
        jedis = pool.getResource();
    }

    //回收连接池资源
    private void _destroy() throws Exception{
        pool.returnResource(jedis);
        pool.destroy();
    }

    public void destroy() throws Exception{
        _destroy();
    }
    
    //产生100线程
    private void _testThread() {
        Thread thread[] = new Thread[100];
        for (int i = 0; i < thread.length; i++) {
            thread[i] = new MyThread();
            thread[i].start();
        }

        for (int i = 0; i < thread.length; i++) {
            try {
                thread[i].join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    //使用smembers取redis集合数据
    class MyThread extends Thread {
        @Override
            public void run() {
                Jedis jedis = JedisPoolClient.pool.getResource();
                Set val = jedis.smembers("10");
                System.out.println(val);
                JedisPoolClient.pool.returnResource(jedis);
            }
    }
}

阅读(3223) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~