Web - Redis & Jedis

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_42986107/article/details/83420121

一、Redis的基本使用

1.Redis是什么?

Redis: 一个开源的高性能键值对(key-value)数据库.
           使用键值对存储数据 - > 存储到内存中(作缓存使用)
Redis服务占用端口号是: 6379 .

2.Redis的安装与使用.

官网下载(Linux版)地址:http://redis.io/download
github下载(window版)地址:https://github.com/MSOpenTech/redis/tags
window版:
           下载好,直接解压即安装完毕!
 
启动: 打开Redis目录中redis-server.exe - > 启动redis服务器
关闭: 关闭窗口 , 就可以关闭Redis服务.
使用: 打开Redis目录中redis-cli.exe -> 启动redis客户端 . 输入命令进行存取.
 
因为每次都要启动redis服务器 , 所以我们可以把它添加到服务中.
在这里插入图片描述
添加实现:

在这里插入图片描述
在这里插入图片描述
添加完成之后 , 我们只需每次启动redis客户端 , 编写命令.

3.Redis的数据类型.

1.字符串类型(string): Map<String , String> 字符串类型是最为基础的数据存储类型!
常用命令:
       set key value 成功   - >   ok
       get key   没有 - >   空(nil)
       del key
       incr key 自增(必须是数字类型的字符串)
       decr key 自减
       incrby key 个数: 每次自增几个.

改: 改是改所有的.

2.哈希类型(hash): Map<String , hashMap<String,String>>

常用命令:
       hset key field value 为指定的key设定field/value对 .
       hmset key field value field value 设定多个.
       hget key field 返回指定key种field的值.
       hmget key field1 field2 .
       hgetall key 获取所有的.
       hdel key field 删除.
改: 改是改某一个.

3.key的通用操作.
       keys : 查看所有的key ,   ? 一个字符 ,    多个字符.
       exists key : 判断key是否存在 .
       type key : 获取指定key的类型.

二、Jedis的基本使用.

1.Jedis是什么?

jedis是用来在客户端上操作Redis的.
使用jedis操作redis需要导入jar包.

2.Jedis的基本操作.

public  void test1(){ 
   //1 设置ip地址和端口      
   Jedis jedis = new Jedis("localhost", 6379);      
   //2 设置数据      
   jedis.set("name", "itheima");      
   //3 获得数据      
   String name = jedis.get("name");      
   System.out.println(name);      
   //4 释放资源
   jedis.close();      
}

3.jedis连接池的使用.

因为jedis连接资源的创建与销毁很消耗程序性能.
所以用连接池 , 不用创建 ,用时获取 , 用完归还.

jedisPool工具类的编写:

public class RedisUtil {
    private static JedisPool pool;
    static {
        // 创建连接池配置对象 , 只创建一个.
        JedisPoolConfig jpc = new JedisPoolConfig();
        // 获取配置文件.
        ResourceBundle bundle = ResourceBundle.getBundle("redis");
        // 获取配置参数.
        String host = bundle.getString("host");
        int port = Integer.parseInt(bundle.getString("port"));
        int minIdle = Integer.parseInt(bundle.getString("minIdle"));
        int maxIdle = Integer.parseInt(bundle.getString("maxIdle"));
        int maxTotal = Integer.parseInt(bundle.getString("maxTotal"));
        int maxWaitMillis = Integer.parseInt(bundle.getString("maxWaitMillis"));

        // 设置参数信息.
        jpc.setMinIdle(minIdle);
        jpc.setMaxIdle(maxIdle);
        jpc.setMaxTotal(maxTotal);
        jpc.setMaxWaitMillis(maxWaitMillis);

        // 获取连接池对象.
        pool = new JedisPool(jpc, host , port);
    }

    public static Jedis getConnection(){
        // 借连接.
        return pool.getResource();
    }
}

redis.properties

host=localhost
port=6379
minIdle=5
maxIdle=10
maxTotal=5
maxWaitMillis=2000

猜你喜欢

转载自blog.csdn.net/qq_42986107/article/details/83420121