Redis study notes

There is a relatively complete tutorial on runoob.com, you can go to see it yourself  http://www.runoob.com/redis/redis-tutorial.html

This article only records some key points in the learning process as study notes

 

install redis

Official description: https://redis.io/download

download, extract, compile

$ wget http://download.redis.io/releases/redis-4.0.1.tar.gz
$ tar xzf redis-4.0.1.tar.gz
$ cd redis-4.0.1
$ make

foreground start

$ cd src
$ ./redis-server

The service is terminated after the foreground starts and exits

start in the background

Find the redis.config file in the installation directory and change daemonize no to daemonize yes

Start with a configuration file

./redis-server ../redis.conf

After startup, you will see the redis process in the background

root     31840     1  0 10:25 ?        00:00:00 ./redis-server 127.0.0.1:6379

 

configuration file

redis.config is the main configuration file of redis, and redis is located in the installation directory

Function parameter illustrate
Start method daemonize no - start in foreground yes - start in background
login password requirepass  password value
bind ip bind

You can only bind the local ip (127.0.0.1), if you want external network access, you can configure *

The port number port Default is 6379

 

Redis data types

Redis supports five data types: string (string), hash (hash), list (list), set (collection) and zset (sorted set: ordered set).

 

Redis commands

When executing the redis command, we first need to start the redis client, the client is under /src

$ cd src
$ ./redis-cli

If redis has a password enabled, you need to enter a password

./redis-cli -a 111111

For remote access, you need to enter the ip and port number

redis-cli -h 123.56.8.122 -p 6379 -a 111111

Introduction to some commands

Order explain
ping Check if the service is running
quit close the current connection
select index switch to the specified database
info Service Information
keys * Get all key values
type key Get the type of saved data
of the key delete a piece of data
exists key  Check if key exists
expire key seconds Specifies the time-to-live for the data. Unit: second
ttl key Returns the remaining time to live. Unit: second
persist key Data is never destroyed
set key value save string data
get key value Take out string data
rpush key value1 [value2] Create or insert list data
lrange key start stop  Get a list of data
fill key  Get the length of the list list
sadd key member1 [member2] Create or insert set data

smembers key

Get a set of data

scard key Get the length of the set list
hmset key field1 value1 [field2 value2 ] Create multiple sets of hash type data
hset key field value Create a set of hash type data
hget key field Get a group of data from the hash table
hdel key field2 [field2] Delete a group of data in the hash table
whale key Get all the data in the hash table

Using Redis in java

Using redis in java requires importing the Jedis package

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

Use the Jedis connection pool to obtain a Jedis instance, and use the instance to implement the function of controlling the redis database. code show as below

package pub.lichao.test.controller;

import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class JedisUtil {
    private JedisPool jedisPool = null; //连接池

    /**
     * 获取连接池
     * @return
     */
    private JedisPool getJedisPool(){
        if (this.jedisPool == null){
            JedisPoolConfig config = new JedisPoolConfig(); //创建连接池配置文件
            config.setMaxTotal(150);//最大连接数,默认8个
            config.setMaxIdle(30);//最大空闲连接数,默认8个
            config.setMinIdle(10);//最小空闲连接数
            config.setMaxWaitMillis(3000);//最大等待时间,毫秒
            config.setTestOnBorrow(true);//获取连接的时候是否检查有效性
            config.setTestWhileIdle(true);//在空闲时是否检查有效性
            //创建连接池
            this.jedisPool = new JedisPool(config, "123.56.8.122", 6379, 6000, "111111");
        }

        return this.jedisPool;
    }

    /**
     * 保存String类型数据
     * @param index 数据库序号
     * @param key 数据key
     * @param value 数据值
     * @param time 生存时间(秒),负数代表永不销毁
     */
    public void saveString(int index,String key,String value,int time){
        //获取Jedis链接实例
        redis.clients.jedis.Jedis jedis = getJedisPool().getResource();
        try{
            jedis.select(index);//选择数据库序号
            jedis.type("String");//选择存储数据的类型
            jedis.set(key,value);//设置string类型数据
            if(time >= 0){
                jedis.expire(key,time);//设置生存时间
            }else{
                jedis.persist(key);//设置永不销毁
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            jedis.close();
        }

    }

    /**
     * 获取String类型数据
     * @param index 数据库序号
     * @param key 数据key
     * @return
     */
    public String getString(int index,String key){
        //获取Jedis链接实例
        redis.clients.jedis.Jedis jedis = getJedisPool().getResource();
        try{
            jedis.select(index);//选择数据库序号
            String value = jedis.get(key);//获取数据值
            return value;
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            jedis.close();
        }

        return null;
    }

    /**
     * 保存List类型数据
     * @param index 数据库序号
     * @param key 数据key
     * @param value 数据值
     * @param time 生存时间(秒),负数代表永不销毁
     */
    public void saveList(int index, String key, String[] value, int time){
        //获取Jedis链接实例
        redis.clients.jedis.Jedis jedis = getJedisPool().getResource();
        try{
            jedis.select(index);//选择数据库序号
            jedis.type("List");//选择存储数据的类型
            jedis.lpush(key,value);//设置string类型数据
            if(time >= 0){
                jedis.expire(key,time);//设置生存时间
            }else{
                jedis.persist(key);//设置永不销毁
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            jedis.close();
        }
    }

    /**
     * 为List类型数据增加值
     * @param index 数据库序号
     * @param key 数据key
     * @param value 值
     */
    public void addList(int index, String key,String value){
        //获取Jedis链接实例
        redis.clients.jedis.Jedis jedis = getJedisPool().getResource();
        try{
            jedis.select(index);//选择数据库序号
            jedis.lpush(key,value);//添加值
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            jedis.close();
        }
    }

    /**
     * 获取List类型数据
     * @param index 数据库序号
     * @param key 数据key
     * @return
     */
    public List<String> getList(int index,String key){
        //获取Jedis链接实例
        redis.clients.jedis.Jedis jedis = getJedisPool().getResource();
        try{
            jedis.select(index);//选择数据库序号
            Long len = jedis.llen(key);//获取列表长度
            List<String> value = jedis.lrange(key,0,len);//获取数据值
            return value;
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            jedis.close();
        }

        return null;
    }

    /**
     * 保存Set类型数据
     * @param index 数据库序号
     * @param key 数据key
     * @param value 数据值
     * @param time 生存时间(秒),负数代表永不销毁
     */
    public void saveSet(int index, String key, String[] value, int time){
        //获取Jedis链接实例
        redis.clients.jedis.Jedis jedis = getJedisPool().getResource();
        try{
            jedis.select(index);//选择数据库序号
            jedis.type("Set");//选择存储数据的类型
            jedis.sadd(key,value);//设置数据
            if(time >= 0){
                jedis.expire(key,time);//设置生存时间
            }else{
                jedis.persist(key);//设置永不销毁
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            jedis.close();
        }
    }

    /**
     * 为Set类型数据增加值
     * @param index 数据库序号
     * @param key 数据key
     * @param value 值
     */
    public void addSet(int index, String key,String value){
        //获取Jedis链接实例
        redis.clients.jedis.Jedis jedis = getJedisPool().getResource();
        try{
            jedis.select(index);//选择数据库序号
            jedis.sadd(key,value);//添加值
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            jedis.close();
        }
    }

    /**
     * 获取Set类型数据
     * @param index 数据库序号
     * @param key 数据key
     * @return
     */
    public Set<String> getSet(int index,String key){
        //获取Jedis链接实例
        redis.clients.jedis.Jedis jedis = getJedisPool().getResource();
        try{
            jedis.select(index);//选择数据库序号
            Set<String> value = jedis.smembers(key);//获取数据值
            return value;
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            jedis.close();
        }

        return null;
    }

    /**
     * 保存Hash类型数据
     * @param index 数据库序号
     * @param key 数据key
     * @param value 数据值
     * @param time 生存时间(秒),负数代表永不销毁
     */
    public void saveHash(int index, String key, Map<String,String> value, int time){
        //获取Jedis链接实例
        redis.clients.jedis.Jedis jedis = getJedisPool().getResource();
        try{
            jedis.select(index);//选择数据库序号
            jedis.type("Hash");//选择存储数据的类型
            jedis.hmset(key,value);//设置hash类型数据
            if(time >= 0){
                jedis.expire(key,time);//设置生存时间
            }else{
                jedis.persist(key);//设置永不销毁
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            jedis.close();
        }
    }

    /**
     * 为Hash类型数据增加值
     * @param index 数据库序号
     * @param key 数据key
     * @param field 域
     * @param value 值
     */
    public void addHash(int index, String key,String field, String value){
        //获取Jedis链接实例
        redis.clients.jedis.Jedis jedis = getJedisPool().getResource();
        try{
            jedis.select(index);//选择数据库序号
            if(jedis.exists(key)){//判断key是否存在
                jedis.hset(key,field,value);//添加值
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            jedis.close();
        }
    }

    /**
     * 获取Hash类型数据
     * @param index 数据库序号
     * @param key 数据key
     * @return
     */
    public Map<String, String> getHash(int index, String key){
        //获取Jedis链接实例
        redis.clients.jedis.Jedis jedis = getJedisPool().getResource();
        try{
            jedis.select(index);//选择数据库序号
            Map<String, String> map = jedis.hgetAll(key);
            return map;
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            jedis.close();
        }

        return null;
    }

    public static void main(String[] args) {
        JedisUtil jedisUtil = new JedisUtil();

        jedisUtil.saveString(0,"testString","string data",300);
        System.out.println(jedisUtil.getString(0,"testString"));

        String[] list = {"value1","value2","value3","value4","value5"};
        jedisUtil.saveList(0,"testList",list,300);
        jedisUtil.addList(0,"testList","value6");
        System.out.println(jedisUtil.getList(0,"testList"));

        String[] set = {"value1","value2","value3","value4","value5"};
        jedisUtil.saveSet(0,"testSet",set,300);
        jedisUtil.addSet(0,"testSet","value6");
        System.out.println(jedisUtil.getSet(0,"testSet"));

        Map<String,String> map = new HashMap<String,String>();
        map.put("field1","value1");
        map.put("field2","value2");
        map.put("field3","value3");
        map.put("field4","value4");
        map.put("field5","value5");
        jedisUtil.saveHash(0,"testHash",map,300);
        jedisUtil.addHash(0,"testHash","field6","value6");
        System.out.println(jedisUtil.getHash(0,"testHash"));
    }
}

Results of the

The above example project has been uploaded to the code cloud: http://git.oschina.net/imlichao/Jedis-example

 

redis windows client

In the windows system, we can use RedisStudio to easily query the redis database

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325445164&siteId=291194637