idea + maven 使用jedis 连接redis

首先添加jar包

jedis(操作redis)、commons-pool(连接池)、junit(测试)

<dependency>
  <groupId>redis.clients</groupId>
  <artifactId>jedis</artifactId>
  <version>2.9.0</version>
</dependency>
<dependency>
  <groupId>commons-pool</groupId>
  <artifactId>commons-pool</artifactId>
  <version>20030825.183949</version>
</dependency>
<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.12</version>
</dependency>

不用连接池连接redis

import redis.clients.jedis.Jedis;

public class RedisUtil {
    private Jedis jedis;
    private String url = "127.0.0.1";
    public RedisUtil(){
        jedis = new Jedis(url);
    }

    public void setDemo(String key,String value){
        jedis.set(key,value);
    }

    public String getDemo(String key){
        String value = jedis.get(key);
        return value;
    }

}


使用连接池连接redis

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

public class RedisUtilPool {
    //Redis 的  地址
    private String url = "127.0.0.1";
    //redis的端口号
    private int port = 6379;
    //可连接的最大数目,默认为8,-1为不限制
    private   int MAX_ACTIVE = 1024;
    //控制一个pool最多有多少个状态为空闲,默认为8
    private int MAX_IDLE = 1024;
    //等待连可用的最大时间,默认为-1表示永不超时
    //如果超时,抛出JedisConnectionException异常
    private int MAX_WAIT = 10000;
    private int TIMEOUT = 10000;
    //在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的;
    private static boolean TEST_ON_BORROW = true;

    private static JedisPool jedisPool = null;


    public RedisUtilPool() throws JedisConnectionException{
        JedisPoolConfig config = new JedisPoolConfig();
        //config.setMaxActive(MAX_ACTIVE);
        config.setMaxIdle(MAX_IDLE);
        config.setMaxWaitMillis(10000);
        config.setTestOnBorrow(TEST_ON_BORROW);
        jedisPool = new JedisPool(config,url,port,TIMEOUT);
    }


    /**
     * 获取Jedis实例
     */

    public Jedis getJedis()throws JedisConnectionException {
        return  jedisPool.getResource();
    }

}


测试

import main.com.NewCode.RedisUtil.RedisUtil;
import main.com.NewCode.RedisUtil.RedisUtilPool;
import org.junit.Test;
import redis.clients.jedis.Jedis;

public class testRedis {
    private RedisUtil redisUtil = new RedisUtil();

    @Test
    public void testRedis(){
        RedisUtil redisUtil = new RedisUtil();
        redisUtil.setDemo("test","1");
        System.out.print(redisUtil.getDemo("test"));
    }

    @Test
    public void testRedisPool() {
        RedisUtilPool redisUtilPool = new RedisUtilPool();
        Jedis jedis = redisUtilPool.getJedis();
        jedis.set("test2", "2");
        System.out.println(jedis.get("test2"));
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值