Linfinity

Never say never.
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

redis实战

Posted on 2020-08-10 21:10  Linfinity  阅读(172)  评论(0)    收藏  举报

一、远程连接redis

Redis的可视化客户端目前较流行的有两个:Redis Desktop Manager(收费) 、 Redis Client(java编写)

 

Redis Client下载地址:https://github.com/caoxinyu/RedisClient/tree/windows/release

 

前提工作:

1、修改redis配置文件   redis.conf (注意备份!)

 

 2、放行6379端口

 

 3、创建连接( 密码不用填

 

4、连接成功

 

 

二、使用Jedis操作redis

1、直接使用(有线程安全问题)

加入依赖

  <dependency>
      <groupId>com.yugabyte</groupId>
      <artifactId>jedis</artifactId>
      <version>2.9.0-yb-16</version>
    </dependency>

使用

 

 

 

2、使用JedisPool

封装JedisPool工具类

package cn.goo.utils;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class JedisPoolUtil {
    private static JedisPool pool;


    //创建JedisPool对象
    public static JedisPool open(String ip, Integer port)
    {
        if(pool == null){
            //1.创建JedisPoolConfig对象,设置参数,创建JedisPool对象
            JedisPoolConfig config = new JedisPoolConfig();
            //设置连接池最大连接数量
            config.setMaxTotal(20);
            //设置最大空闲数
            config.setMaxIdle(2);
            //设置检查项为true,表示从线程池里取出的对象一定是检测可用
            config.setTestOnBorrow(true);

            //2.创建Pool对象
            /**
             *
             */
            pool = new JedisPool(config, ip, port, 6000);

        }
        return pool;
    }

    //关闭Pool对象
    public static void close()
    {
        if(pool != null)
        {
            pool.close();
        }
    }


}

 

在main中使用

 public static void main(String[] args) {
        JedisPool pool = null;
        Jedis jedis = null;

        String ip = "127.0.0.1";
        Integer port = 6379;

        try{
            pool = JedisPoolUtil.open(ip, port);
            jedis = pool.getResource();


            jedis.set("email","111@qq.com");
            String email = jedis.get("email");
            System.out.println(email);
        }
        finally {
            if(jedis != null)
            {
                //关闭jedis资源对象,将其放回pool,以供其他请求使用
                jedis.close();
            }
        }


    }