Redis简单操作

简单通过Jedis工具连接Redis,操作相关 key

Maven依赖

<dependency>
     <groupId>redis.clients</groupId>
      <artifactId>jedis</artifactId>
      <version>2.9.0</version>
 </dependency>
 <dependency>
       <groupId>org.apache.commons</groupId>
       <artifactId>commons-pool2</artifactId>
       <version>2.6.0</version>
  </dependency>

简单测试

package com.example.redispratice;

import org.junit.Test;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * redis连接测试  默认使用0分区
 * 1.简单连接   2.使用连接池
 * @author Chen
 * @date 2021/9/7 - 15:40
 */
public class TestSample {

    /**
     * 使用简单的redis连接
     */
     @Test
     public void test() {
       Jedis jedis = new Jedis("127.0.0.1", 6379);
       jedis.auth("123456");
       jedis.set("test", "hello redis");
       jedis.expire("test",20);
       while (jedis.ttl("test") > -1){
           System.out.println(jedis.get("test")+" 值剩余存活时间:"+jedis.ttl("test"));
           if (jedis.ttl("test") == 1){
               System.out.println("game over , the key 【test】 was destroy");
           }
           try {
               Thread.sleep(1000);
           } catch (InterruptedException e) {
               e.printStackTrace();
           }
       }
       jedis.close();
     }


    /**
     * 使用连接池连接redis测试
     */
    @Test
    public void testPool() {
       JedisPoolConfig poolConfig = new JedisPoolConfig();
       poolConfig.setMaxIdle(20);
       poolConfig.setMinIdle(10);
       poolConfig.setMaxTotal(30);
       poolConfig.setMaxWaitMillis(3000);
       poolConfig.setTestOnBorrow(true);
       poolConfig.setTestOnReturn(true);
       JedisPool jedisPool = new JedisPool("127.0.0.1", 6379);
       Jedis jedis = jedisPool.getResource();
       jedis.auth("123456");
       System.out.println(jedis.get("new"));
       jedis.close();
       jedisPool.close();
     }
}

参考常用操作

redis常用类型操作

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值