天天看點

java程式設計:jedis連接配接redis資料庫執行個體

package demo;

import org.junit.Test;

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

/**
 * jedis的測試
 */

public class mydemo {
    /**
     * 連接配接redis
     */

    @Test
    public void demo1() {
        //連接配接redis
        Jedis jedis = new Jedis("localhost", 6379);
        //設定
        jedis.set("name", "Tom");
        //擷取
        String name = jedis.get("name");
        System.out.println(name);
        //關閉
        jedis.close();  
    }


    /**
     * redis連接配接池
     */
    @Test
    public void demo2() {
        // 獲得連接配接池的配置對象
        JedisPoolConfig config = new JedisPoolConfig();
        // 最大連接配接數
        config.setMaxTotal(30);
        // 最大空閑連接配接數
        config.setMaxIdle(10);

        //獲得連接配接池
        JedisPool jedisPool = new JedisPool(config, "localhost", 6379);

        // 獲得Redis對象
        Jedis jedis = null;

        try {
            // 通過連接配接池獲得連接配接
            jedis = jedisPool.getResource();
            jedis.set("name", "張三");
            String name = jedis.get("name");
            System.out.println(name);
        }
        catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        finally{
            // 關閉redis連接配接
            if (jedis != null) {
                jedis.close();
            }
            if (jedisPool != null) {
                jedisPool.close();
            }
        }
    }

}