在idea下去连接redis

1.首先我们如果是maven项目的话,需要先将redis的包导入进来,所以,在pom文件中先加上以下代码

<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.8.0</version>
</dependency>

2.可以通过原始的jdbc连接数据库,也可以通过连接池去连接。

下面是一段测试代码。

①通过jdbc去连接

String host = "192.168.59.160";
int port = 6379;
Jedis jedis = new Jedis(host,port);
jedis.set("age","18");
String age = jedis.get("age");
String name = jedis.get("name");
System.out.println(age+":"+name);

②封装工具类:

最大连接数:连接池中最多存在的连接数。

最大空闲数:连接超出时,以最大空闲数为准。

最小空闲数:第一需要释放资源,次初始化连接池默认的连接数。

private static JedisPool jedisPool;
static {
    InputStream stream = Utils.class.getClassLoader().getResourceAsStream("redis.properties");
    Properties properties = new Properties();
    try {
        properties.load(stream);
    } catch (IOException e) {
        e.printStackTrace();
    }
    String host = properties.getProperty("redis.host");
    int port = Integer.parseInt(properties.getProperty("redis.port"));
    int max_total = Integer.parseInt(properties.getProperty("redis.max_total"));
    int min_Idle = Integer.parseInt(properties.getProperty("redis.Min_Idle"));
    int max_Idle = Integer.parseInt(properties.getProperty("redis.Max_Idle"));
    JedisPoolConfig poolConfig = new JedisPoolConfig();
     poolConfig.setMaxTotal(max_total);
     poolConfig.setMinIdle(min_Idle);
     poolConfig.setMaxIdle(max_Idle);
     jedisPool = new JedisPool(poolConfig,host,port);
}
public static Jedis getJedis(){
    return jedisPool.getResource();
}

public static void closeJedis(Jedis jedis){
    if(jedis!=null){
        jedis.close();
    }
}

我在maven的entity层的resource中加了一个配置文件。

 

 

然后加可以在我们的测试代码中写

@Test
public void add(){
    Jedis jedis = Utils.getJedis();
    String s = jedis.set("address", "河南");
    System.out.println(s);//OK是成功 NIL是失败
}

这样就简单的实现了在idea下连接redis。

下篇文章更新redis五大基本数据类型的使用。

  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 11
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值