Redis installation, configuration file explanation and usage scenarios of five commonly used data types

Redis

What is Redis?

  1. Comply with the BSD protocol: you can modify the code and republish at will, strong customization, open source and free
  2. It is a high-performance Nosql (Key-Value) database, non-relational database
  3. The data is placed in the memory and read very fast, but it consumes memory and supports data persistence: timed snapshots, based on two persistence mechanisms of aof; generally used together

Why use Redis?

  1. Traditional relational databases cannot meet the requirements for high concurrent reading and writing, and their performance is relatively low. Redis non-relational database data is stored in memory, so the speed is extremely fast, which greatly reduces the burden on relational databases
  2. Redis generation solves the complexity problem of large-scale data and multiple attribute data types
  3. It can easily solve many complex scene applications, such as: setting data expiration time; website access hits; cache; hot data; ranking list; message system, etc.

How to use Redis?

Install:

Redis Chinese website: http://www.redis.cn/download.html

  1. Install the gcc environment:yum install -y gcc gcc-c++
    insert image description here

  2. Unzip to the opt directory:tar -zxvf redis-5.0.7.tar.gz -C /opt
    insert image description here

  3. Enter the redis decompression directory to compile:make
    insert image description hereinsert image description here

  4. Execute the installation in this directory:make PREFIX=/usr/local/redis install
    insert image description here

  5. Start: enter the redis installation directory to execute ./bin/redis-serverthe start server
    insert image description here

  6. Create a new command window to start the client: ./bin/redis-cli
    insert image description here
    the installation is complete, you can exit the two clients through ctrl+c

Redis configuration file

  1. First make a backup of the redis.conf configuration file:cp redis.conf /usr/local/redis
    insert image description here
  2. Configuration file introduction
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#注释掉这一行,不然只能在本机访问redis
#bind 127.0.0.1   


protected-mode yes

#Redis默认端口号
port 6379


tcp-backlog 511

#客户端闲置多长时间关闭,0的话代表不开启此功能
timeout 0


tcp-keepalive 300

#redis默认不是守护进程启动,开启守护进程把参数变为yes
daemonize no



supervised no


#守护进程启动时redis会把pid写入这个文件中
pidfile /var/run/redis_6379.pid

#记录日志级别共四个级别:debug,verbose,notice,warning
loglevel notice
#日志记录方式
logfile ""

#设置数据库数数量,默认提供16个
databases 16

#指定多长时间内,有多少次更新操作就会同步到数据文件(持久化)
save 900 1
save 300 10
save 60 10000


stop-writes-on-bgsave-error yes

#压缩持久化文件
rdbcompression yes


rdbchecksum yes

# 数据持久化到硬盘的文件名称
dbfilename dump.rdb

#持久化文件放到当前文件目录下
dir ./

#设置数据库密码默认没有
requirepass foobared

start using

First of all, if you want to use a visual connection, you need to set the redis password: modify the configuration file
insert image description here

Common command key management

keys *#返回满足的所有键,可以模糊匹配如:keys asb*
exists key #是否存在指定的key,存在返回1,不存在返回0
expire key secode #设置某个key的过期时间,单位秒
del key #删除某个key
ttl key #查看剩余时间,当key不存在时返回-2,存在但没有设置剩余生存时间,返回-1,否则,以秒为单位,返回key的剩余生存时间
persist key #取消过期时间
PEXPIRE key millisecodes: #修改key的过期时间为毫秒
select #选择数据库 0-15(默认16个数据库),多个数据库是为了数据的安全和备份
move key dbundex #将当前数据中的key转移到其他数据库
randomkey #随即返回一个key
rename key key2 #重命名key
echo #打印命令
dbsize #查看数据库中key的数量
info #查看数据库信息
config get #实时存储收到的请求,返回相关的配置
flushdb #清空当前的数据库
flushdball #清空所有的数据库

key naming convention

  1. The key should not be too long, otherwise the small memory will reduce the query efficiency
  2. The key should not be too short, too short for poor readability
  3. It is best to use a unified naming convention for keys in a project, such as
  4. key is case sensitive

The five most commonly used data types in Redis

String command === Java String string

Introduction :

  1. String is the most basic data type of Redis, and a key can store up to 512MB
  2. The simplest key-value type of String data structure, value is not only a string, but also a number, which is a special type that contains many types
  3. The String type is binary safe and can contain arbitrary data, such as: serialized object storage, binary storage of a picture, a simple string value, etc.

Order

set key  value   #指定一个key赋值,多次设置相同的key会覆盖之前的值
setnx key1 value #如果key不存在设置该值并返回1,若存在不进行任何操作返回0
setex key 10 tiantian 设置key的过期时间为10秒。10秒后删除该key
settrange string range value #替换字符串 


get key #根据key去除value,不存在返回nil
getrange key start end #用于获取存储在指定key中字符串指定的子字符串,包括start和end
getbit key offset #获取key所存储的字符串值,获取指定偏移量的位
getset key name #指定key的值并返回之前的旧值,当key为空时返回nil
strlen key #返回key所存储的字符串值的长度


del key #删除指定key,如果存在返回值数字类型
incr num #自增,将value存储的值自增加一
decr num #自减
String application scenarios
  1. string is usually used to hold a single string or json string data
  2. Because string is binary safe, it is completely possible to store the content of a picture as a string
  3. Counters (Weibo fans, hits, SMS verification codes, votes, etc.)
Hash type == Java's Map

Introduction :

  1. Suitable for storing objects, occupying less memory space than string

Order

hset key field value #设置键值
hmset key field1 value1 field2 value2 #可以一次设置多个值

hget key field #获取存储到hash中的值根据field获取value
hmget key field field2 #一次获取多个值
hgetall  key #获取所有字段和值

hkeys key #获取所有哈希表中的字段
hlen key #获取哈希表中字段的数量

hdel key field1 ... #删除指定field的值

hsernx key field value #只有在字段field不存在时,设置字段值
hincrby key field increment #为指定整型值增加increment
hexists key field #查看是否存在
Application Scenario
  1. Store a user information data, it is the type closest to the relational database, the operation object is more convenient than string
  2. What is stored is actually a heshmap
Redis integrates SpringBoot
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>boot-Jedis</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.2.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
    </dependencies>

</project>

Global configuration files, generally do not need to understand

server:
  port: 8080
spring:
  redis:
    port: 6379
    password: root  #改成自己的
    host: 181.72.39.145 #改成自己的
    jedis:
      pool:
        max-idle: 6 #最大空闲数
        max-active: 10 #最大连接数
        min-idle: 2 #最小空闲数
    timeout: 5000 #连接超时

configuration class

package site.tian.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

@Configuration
@Slf4j
public class JedisConfig {
    
    

    @Value("${spring.redis.host}")
    private String host;

    @Value("${spring.redis.port}")
    private int port;

    @Value("${spring.redis.password}")
    private String password;

    @Value("${spring.redis.timeout}")
    private int timeout;

    @Value("${spring.redis.jedis.pool.max-active}")
    private int maxActive;

    @Value("${spring.redis.jedis.pool.max-idle}")
    private int maxIdle;

    @Value("${spring.redis.jedis.pool.min-idle}")
    private int minIdle;

    @Bean
    public JedisPool jedisPool() {
    
    
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxIdle(maxIdle);
        jedisPoolConfig.setMinIdle(minIdle);
        jedisPoolConfig.setMaxTotal(maxActive);

        JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout, password);
        log.info("JedisPool连接成功"+host+"\t"+port);
        return jedisPool;
    }
}

It is recommended to use lettuce

 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <!--必须-->
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
        </dependency>
set is similar to java's HashTable collection (unordered)
Application of long scene

Commonly used in data intersection, union, and difference operations between two sets

  1. Using the set operation, you can take the intersection of different interest circles, so as to realize common attention, second-degree friends and other functions very conveniently
  2. Using uniqueness, we can count all independent IPs visiting the website and access active users
Zset is similar to java's HashTable collection (ordered)

orderly without repetition,

Application of long scene

Sales ranking points ranking, mainly can be sorted

Guess you like

Origin blog.csdn.net/weixin_44078653/article/details/104668756