Redis series articles: Redis series (I) – Installation and Startup Redis series (II) – Syntax and commands

I. Introduction to Redis

Redis is a type of NoSql, but before we figure out what Redis is, let’s understand what NoSql is.

1. What is NoSql

NoSql, full name: Not Only Sql, is a non-relational database, it can Not replace the relational database, Only a supplement of the relational database, is to solve a series of problems such as high concurrency, high availability, high expansion, big data storage and database solutions.

NoSql is classified into four categories: key-value database, column database, document database, and Graph database. Redis falls into the first category: key-value storage databases.

2. What is Redis

Redis is a high performance key-value database developed in C language, that is, through some key-value types to store data. Redis supports the following key types: String, MAP hash, List, set, sortedSet.

Redis is used in the following scenarios: caching (data query, short connection, news content, product content, etc.), session separation in distributed cluster architecture, online friend lists in chat rooms, and task queues. (Seckill, Snap, 12306, etc.), app leaderboards, website visit statistics, data expiration processing (accurate to the millisecond). Among them, the application scenario as cache is the most.

Two, Redis installation

Generally, Redis is installed on Linux server, so this example is introduced under Linux installation, if your computer is Windows or MAC, please baidu installation method.

The Linux operating system used in this example is CentOS6.7. The commands used in Linux operating systems such as Ubuntu may vary. Learn about them by yourself.

1, download

Can find all the redis to redis website version of the download address, such as: download. Redis. IO/releases/re…

2, installation,

After connecting to Linux using server terminal connection software such as Xshell, perform the following operations:

1) Download and compress Redis

Download redis:

Wget HTTP: / / http://download.redis.io/releases/redis-3.0.0.tar.gzCopy the code

Run ll to view all files in the current directory

Redis-3.0.0.tar. gz is the redis-3.0.0.tar.gz package.

The tar - ZXVF redis - 3.0.0. Tar. GzCopy the code

Then run ll to view all files in the current directory

2) Compile and install Redis

Redis source code:

cdRedis - 3.0.0Copy the code

Redis = Redis = Redis = Redis = Redis = Redis

makeCopy the code

CentOS has its own C language environment. If other Linux operating systems do not have c language environment, you need to install the yum install gcc-C ++ command

The Redis installation command is as follows:

make install PREFIX=/usr/local/redisCopy the code

In this command, “make install PREFIX=” is fixed, and “/usr/local/redis” is the installation directory of redis.

Finally, check whether Redis is installed successfully:

cd /usr/local/redis/Copy the code

Run the ll command to view the bin folder, indicating that Redis has been successfully installed.

3. Redis start and stop

Redis has two startup types: front-end startup and back-end startup. To start Redis, you need to go to the bin directory of Redis to start the command.

1. Front-end start and stop

1) Commands for front-end startup:

[root@localhost bin]# ./redis-serverCopy the code

You can see that the Redis startup port is 6379 (the default), and the process ID is 5979. Also, after the front end starts Redis, the terminal will enter the Redis console, and there is no way to continue with other Linux commands, that is, the terminal window will be “disabled”, only the Redis command can enter.

2) Close command of front-end startup:

Forcible shutdown: Ctrl+ C Normal shutdown: [root@localhost bin]# ./redis-cli shutdownCopy the code

Here’s a comparison of the two commands:

  • Forcing a shutdown can be done directly from the Redis console (Redis may lose some data).
  • Closing normally requires opening another terminal window (Redis does not lose data and is recommended).

Note that once the shutdown command is executed, the Redis console is shut down and the Redis service is stopped.

2. Back-end start and stop

Back-end startup is definitely the way we will use in development, but after using the back-end startup command, you need to do the following configuration:

1) Back-end startup configuration:

The first step is to copy the redis. Conf file from the redis source directory to the bin directory of the redis installation directory.

Conf file, change the value of daemonize to yes and save.

[root@localhost bin]# vim redis.conf Copy the code

Linux vim editor instructions please learn by yourself, here is a few of the most commonly used vim commands:

I: Enter editing mode.

Esc: Exit edit mode and enter Browse mode (enter vim editor, which is browse mode by default).

:wq: Save the changes and exit the vim editor.

After the above steps of configuration, there is no need to configure, the following command can be used to start the redis background.

2) Back-end startup commands:

[root@localhost bin]# ./redis-server redis.confCopy the code

Redis. conf, which means that redis will run according to the configuration of the configuration file. At the same time, you can also see that after starting the redis background, the terminal will not enter the Redis console, which is to run the background. We can check whether the system now has redis process:

[root@localhost bin]# ps -aux | grep redisCopy the code

You can see that Redis is running with port 6379 and process ID 6087.

3) Shutdown command for back-end startup:

Forcibly disable: [root@localhost bin]# kill -9 Process IDNormal shutdown: [root@localhost bin]# ./redis-cli shutdownCopy the code

There is no way to forcibly shut down Redis by CTRL + C, as there is when you start redis on the back end. If you need to forcibly shut down Redis, you can only kill the process. The normal command to shut down Redis is the same as the front end shutdown, so no more nonsense here.

Normal shutdown is recommended for projects. If redis is used as a cache, the data is stored in memory. If redis is turned off normally, the memory data will be persisted locally and then closed. If forcibly shut down, persistent operations are not performed and some data may be lost.

4. Redis client

1. Redis has its own client

In the previous introduction to the structure of the bin directory in the Redis installation directory, the redis client has been marked, which is redis- CLI. This client has two common functions:

  • Used to shut down the Redis service.
  • Let the terminal access the Redis console (used when running Redis in the background).

1) start

Start client command:

[root@localhost bin]#./redis-cli -h 127.0.0.1 -p 6379Copy the code
  • -h: specifies the IP address of the redis server
  • -p: specifies the port of the redis server to be accessed

If the default IP address and port are used, the command can be written as follows:

[root@localhost bin]# ./redis-cliCopy the code

Use the default configuration: default IP [127.0.0.1], default port [6379]

2) shut down

CTRL + c 127.0.0.1:6379 > quitCopy the code

To shut down the client, use either command without affecting the redis data.

2. Graphical interface client

There is a redis graphical client software called Redis-destop-Manager. This is the download page of the software, which supports Windows, Mac OS X and Linux. Please choose to download the software according to your computer system. Here, take Windows as an example, briefly talk about the use of the software, installation is very simple, all the way to the next step, and then open the application.

1) Open the Redis server connection configuration

2) Add the Redis server connection and test whether the connection is successful

3) View all databases in redis server

4) View key-value pair data in individual databases

3. Code control client

Redis can not only use commands to operate, currently basically mainstream languages have client support, such as: Java, C, C#, C++, PHP, Node.js, Go and so on.

There are some Java clients in the official website, such as Jedis, Redisson, Jredis, jDBC-redis, etc. Jedis and Redisson are officially recommended. Jedis is most commonly used in the enterprise. Jedis is hosted on Github, click open.

1) Simple redis use

Step 1: Import the following two JAR packages

  • Jedis – 2.7.0. Jar
  • Commons – pool2-2.3. The jar

Step 2: Create a Jedis connection using the Redis server

@Test
public void jedisClient() {// create Jedis Jedis Jedis = new Jedis()"192.168.128.128", 6379); // assign Jedis to jedis.set("s2"."222"); String s2 = jedis.get("s2"); System.out.println(s2); // Close Jedis jedis.close(); }Copy the code

Step 3: Use the Jedis connection pool to get the Jedis

@Test
public void jedisPool() {
    // JedisPool
    JedisPool jedisPool = new JedisPool("192.168.128.128", 6379); Jedis jedis = jedispool.getResource (); String s2 = jedis.get("s2"); System.out.println(s2); // Close the jedis client jedis.close(); // Close the connection pool jedispool.close (); }Copy the code

2) Spring integration with jedisPool

The first step:

  • Add the Spring JAR package
  • Configure the Spring configuration file applicationContext.xml
<? xml version="1.0" encoding="UTF-8"? > <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
        xsi:schemaLocation="Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd"> <! Connection pool configuration --> <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig"> <! -- Maximum number of connections --> <property name="maxTotal" value="30"/ > <! -- Maximum number of free connections --> <property name="maxIdle" value="10"/ > <! -- The maximum number of connections released at a time --> <property name="numTestsPerEvictionRun" value="1024"/ > <! -- Release connection scan interval (ms) --> <property name="timeBetweenEvictionRunsMillis" value="30000"/ > <! -- Connection minimum idle time --> <property name="minEvictableIdleTimeMillis" value="1800000"/ > <! When the idle time > this value and idle connections > the maximum number of idle connections --> <property name="softMinEvictableIdleTimeMillis" value="10000"/ > <! -- Maximum number of milliseconds to wait to get a connection, less than zero: block indefinite time, default -1 --> <property name="maxWaitMillis" value="1500"/ > <! Check the validity of the connection when obtaining it, defaultfalse -->
            <property name="testOnBorrow" value="false"/ > <! -- Check validity when idle, defaultfalse -->
            <property name="testWhileIdle" value="true"/ > <! -- Whether the connection is blocked when exhausted,falseAn exception is reported, true blocks until timeout, defaulttrue -->
            <property name="blockWhenExhausted" value="false"/> </bean> <! -- Redis standalone through connection pool --> <bean id="jedisPool" class="redis.clients.jedis.JedisPool"
            destroy-method="close">
            <constructor-arg name="poolConfig" ref="jedisPoolConfig" />
            <constructor-arg name="host" value="192.168.128.128" />
            <constructor-arg name="port" value="6379" />
        </bean>
    </beans>Copy the code

Step 2: Test the code

@Test
public void testJedisPool() {
    JedisPool pool = (JedisPool) applicationContext.getBean("jedisPool");
    Jedis jedis = null;
    try {
        jedis = pool.getResource();

        jedis.set("name"."lisi");
        String name = jedis.get("name");
        System.out.println(name);
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        if(jedis ! = null) {// Close connection jedis.close(); }}}Copy the code

Five, the other

1. Redis database quantity configuration

By default, 16 databases are created in redis. If you need to change the number of databases, you can change the value of databases in the redis.

2. Redis database selection

Redis uses a database with subscript 0 by default. To switch a database, use the “Select subscript” command in the Redis console to select the database.

127.0.0.1:6379 > select 15Copy the code

3, problem,

If you cannot connect to the server using terminal software like Xshell, please check whether port 22 is open in Linux system. You can open port 22 by modifying iptable blocking rules. If you use Ali Cloud server, you need to modify security group rules.