Redis single service construction, use, eight types, transactions, springboot integration of redis, old framework using redis, etc.

        This article will mainly introduce: the establishment of redis single service, some common configurations of redis configuration files, some common commands of the five basic types of redis and three special types, redis transactions, the use of springboot integrated redis, and the previous old framework or How to use redis without a framework.


Table of contents

Preface

1. What is Redis

2. Building Redis single service on Linux system

1. Redis official website download address Download | Redishttps://redis.io/download/

2. Redis single service installation

3. Detailed explanation of common configuration files of Redis.conf

4. Redis performance test

5. Eight major types of Redis and their commonly used commands (five basic types, three special types)

1. String string

2. List ordered list

3. Set is an unordered and non-repeating collection

4. hash hash

5. zset ordered set

6. geospatial geographical location

7. Statistics of hyperloglog cardinality

8. bitmap bitmap

6. Redis transactions

7. Spring boot integrates Redis use

1. The fastest way to use (use default configuration)

2. Customize the way to configure beans

3. Annotation method

8. How to use Redis in other old frameworks

Afterword


Preface

Redis is already a technology that is often used nowadays. The current concurrency can easily reach tens of thousands or hundreds of thousands. It is difficult to support without caching technology. Compared with other caching technologies, redis provides It supports persistence operations, clusters, transactions, multi-language APIs, etc., and is based on memory operations, with very fast reading and writing speeds.


1. What is Redis

        The full name of redis: Remote Dictionary Server (Remote Dictionary Service), is an open source log type, key-value database (NoSql type database) written in C language, supporting network, based on memory and also durable, and provides multiple languages API (Baidu Encyclopedia).

        Features of redis:

                1. Provide efficient caching technology.

                2. Supports diverse data and can be persisted.

                3. Service clusters can be built.

                4. Support affairs.

                5. Single-threaded pure memory operation can avoid frequent context switching.

        Note: Don’t think that redis is slow just because it is single-threaded. The maximum read speed of redis can reach 110,000 times/s and the write speed is 81,000 times/s, which is super fast!

2. Building Redis single service on Linux system

        1. Redis official website download address Download | Redis https://redis.io/download/         2. Redis single service installation

                ① Download the redis compressed file and upload it to the /opt path of the Linux server, and decompress: tar -zxvf redis-6.2.6.tar.gz

                ② redis operating environment installation: yum install gcc-c++

                ③ Enter the decompressed directory and execute: make and make install

                

                ④ In order to facilitate subsequent modifications, copy the redis.conf file in the decompressed directory and save it to a convenient location. Place it here under the self-created directory/bug/redis (you can also use the original configuration file, but not have any impact)

                 ⑤ Modify the redis.conf file and change it to start in the background (you may not modify it, but redis starts in the foreground by default, and the process will be closed as soon as you exit): vim redis.conf

 

                 ⑥ Start redis using our own configuration file:

Enter the installation directory: cd /usr/local/bin/

Start using the specified configuration file: redis-server /bug/redis/redis.conf

Check whether the process has been started: ps -ef|grep redis

Close the redis service: shutdown (needs to be executed after connecting to redis)

Kill the redis process: kill -9 process id

                 ⑦ Connect to redis and test whether it starts successfully: redis-cli -p 6379 (The installation of single-service redis is complete! Isn’t it super simple!)

                 

3. Detailed explanation of common configuration files of Redis.conf

bind 127.0.0.1                    #运行地址,默认本机运行
protected-mode yes                #是否受保护的模式,默认yes
port 6379                         #端口号,默认6379
daemonize no                      #是否后台启动,默认no,一般会改为yes
loglevel notice                   #日志级别,默认notice,可以设置为debug、warning等
logfile ""                        #日志的文件名
databases 16                      #数据库数量,默认16
save 3600 1 300 100 60 10000      #持久化操作,3600秒内有1个修改/300秒内有100个修改等则持久化一次
stop-writes-on-bgsave-error yes   #持久化失败后是否继续运行,默认yes
rdbcompression yes                #是否压缩持久化的文件,默认yes
rdbchecksum yes                   #持久化校验,默认yes
dbfilename dump.rdb               #持久化文件名称,redis默认使用的是rdb持久化,还有一种是aof
appendonly no                     #这种就是aof方式持久化,默认是关闭的
appendfilename "appendonly.aof"   #开启aof持久化时,生成的.aof文件,文件名称配置
requirepass xxxxxx                #redis设置密码
maxclients 10000                  #客户端最大连接数

4. Redis performance test

        Test conditions: Use 1,000 concurrent clients and send 10,000 requests (be careful not to try too many requests. I tried 1 million, but it took a long time to finish)

        Test statement: redis-benchmark -h 127.0.0.1 -p 6379 -c 1000 -n 10000 (note the decompression directory: cd /usr/local/bin/)

        Test result analysis: Only one get request is analyzed here, and other requests have the same description.

====== GET ====== (get request)
  10000 requests completed in 0.16 seconds (the total time used by 10,000 get requests is 0.16 seconds)
  1000 parallel clients (1,000 different clients)
  3 bytes payload (3byte data each time)
  keep alive: 1 (1 redis server)
  host configuration "save": 3600 1 300 100 60 10000 (some of your own configurations)
  host configuration "appendonly": no (whether there is compression, The default is no)
  multi-thread: no (whether it is multi-threaded)

Latency by percentile distribution:
0.000% <= 5.991 milliseconds (cumulative count 1)
50.000% <= 11.383 milliseconds (cumulative count 5005)
75.000% <= 13.743 milliseconds (cumulative count 7502) (Some parts were deleted, otherwise it would be too long and inconvenient to view)
99.994% <= 24.431 milliseconds (cumulative count 10000)
100.000% <= 24.431 milliseconds (cumulative count 10000) (10,000 requests processed Completed in 24.431 milliseconds)

Cumulative distribution of latencies: (The final percentage of requests processed is almost the same as above, no explanation)
0.000% <= 0.103 milliseconds (cumulative count 0)
0.130% <= 6.103 milliseconds (cumulative count 13) (some are also deleted in the middle)
99.750% <= 24.111 milliseconds (cumulative count 9975)
100.000% <= 25.103 milliseconds (cumulative count 10000)

Summary:
  throughput summary: 60975.61 requests per second (At the above speed, an average of 60975.61 requests can be processed in 1 second)
  latency summary (msec): (These are some introductions to the above percentages)
          avg min p50 p95 p99 max
       11.646 5.984 11.383 18.399 23.199 24.431

        Some common parameters for testing (redis-benchmark -h 127.0.0.1 -p 6379 -c 1000 -n 10000):

serial number Options describe default value
1 -h Specify server hostname 127.0.0.1
2 -p Specify server port 6379
3 -s Specify server socket
4 -c Specify the number of concurrent connections 50
5 -n Specify the number of requests 10000
6 -d Specifies the data size of the SET/GET value in bytes 2
7 -k 1=keep alive 0=reconnect 1
8 -r SET/GET/INCR uses random keys, SADD uses random values
9 -P Pipe  <numreq> requests 1
10 -q Force quit redis. Show only query/sec values
11 --csv Output in CSV format
12 -l Generate loops that execute tests forever
13 -t Run only a comma-separated list of test commands.
14 -I Idle mode. Open only N idle connections and wait.

        Ola, the introduction to redis testing is complete. The commonly used parameters for these tests are from the redis Chinese official website: https://www.redis.net.cn/

5. Eight major types of Redis and their commonly used commands (five basic types, three special types)

        1. String string

instruction Features
set key1 "xiaobug" Create a key with key1 and value xiaobug. (Note: Do not use the set command casually, it is very dangerous. If the key is repeated, the original value will be overwritten. It is recommended to use setnx)
setnx key1 "xiaobug" First determine whether the key key1 exists. If it does not exist, the key key1 will be created. If it exists, creation is not allowed.
mset key1 "xiaobug" key2 "xxx" Create keys in batches, for example: two keys key1 and key2 are created here, with values ​​xiaobug and xxx respectively (this method is not recommended)
msetnx key1 "xiaobug" key2 "xxx" Create keys in batches, but first determine whether keys key1 and key2 exist. (Note: As long as one of key1 and key2 exists, the creation will fail. Only when neither key1 nor key2 exists, the creation will be successful. It is an atomic operation.)
setex key1 10 "xiaobug" Create a key named key1, which will expire after 10 seconds and its value is xiaobug.
ttl key1 Query the remaining expiration time of this key key1 (when -2 is returned, it means the key has been destroyed)
del key1 Delete the key whose key is key1
get key1 Query the value of key1
mget key1 key2 Batch query values, such as: the query keys here are the values ​​in key1 and key2 respectively
strlen key1 Query the key named key1 and its value string length
exists key1 Query whether the key1 key exists
getrange key1 0 5 Query the key named key1 and intercept the string, starting from the 0th position and ending at the 5th position. For example: the original value is "xiaobug", then the query is "xiaobu". Note: This is just a query and will not change the value in key1. getrange key1 0 -1 (query all values)
setrange key1 2 "000" Replace the value, give the key named key1, the value starts from subscript 2, replace the 3 digits with "000", for example: the original value is "xiaobug", after execution it is "xi000ug"
keys *  Query the names of all keys in the current library
append key1 "xiaobug"

For the key named key1, concatenate a string "xiaobug", for example: it used to be "value1", but now it is "value1xiaobug".

If there is no key key1, add a new key named key1 with the value "xiaobug"

incr key1 Given a key named key1, its value is incremented by 1, similar to i++ in Java. (Note: Values ​​can only be integers)
decr key1 Given a key named key1, its value is decremented by 1, similar to i-- in Java. (Note: Values ​​can only be integers)
incrby key1 10 Given a key named key1, its value is incremented by 10. (Note: Both values ​​can only be integers)
decrby key1 10 Given a key named key1, its value is decremented by 10. (Note: Both values ​​can only be integers)
getset key1 "xiaobug" To combine instructions, first get the query data, and then perform set assignment. For example: the original value is: xxx. After executing this command, the value will be returned first: xxx, and then the original value will be replaced: xiaobug. (Actually, it lets you take another look at the value before it is replaced. There are still many places to use it)
flushdb Clear all data in the current database (note: redis has 16 databases by default, but it defaults to the 0th database)
flushall Clear all databases

2. List ordered list

instruction Features
lpush key1 "xiaobug"

Create a key named key1, and the first value is xiaobug. If key1 already exists, the value will be added to the leftmost.

For example: the original value {0: xxx}, the value after executing the instruction is {0: xiaobug, 1: xxx}

rpush key1 "xiaobug"

Create a key named key1, and the first value is xiaobug. If key1 already exists, the value will be added to the right.

For example: the original value {0: xxx}, the value after executing the instruction is {0: xxx, 1: xiaobug}

lset key1 0 "xiaobug" Modify (overwrite) the value in the specified subscript, 0 represents the first position, 1 represents the second position...
linsert key1 before "bug" "xxx" Insert data before and after the specified value, before means before, after means after, for example: the original value {0: xiao, 1: bug}, after executing the instruction, it will be {0: xiao, 1: xxx, 2: bug}
lindex key1 0 Get the value of an element in the key key1 through the subscript, 0 means the first, 1 the second, 2 the third...
range key1 0 1 Specify the length to query the set whose key is key1. For example: the original value is {0: xxx, 1: xiaobug, 2: yyy}, then the query is {0: xxx, 1: xiaobug}. range key1 0 -1 means query all
llen key1 Get the length of the set in key key1
lpop key1

Removes an element from the leftmost element of key key1. For example: the original value is {0: xxx, 1: xiaobug, 2: yyy},

After executing the instruction, it is {0: xiaobug, 1: yyy}

rpop key1 Remove an element from the rightmost element of key key1
lrem key1 1 "xiaobug" Delete an element with the value "xiaobug" in key1, 1 means one, 2 means two, 3 means three...
ltrim key1 0 1

Intercepting a collection is similar to Java's substring, except that the original value will be modified in redis, such as: the original value {0: xxx, 1: xiaobug, 2: yyy}, and the value after executing the instruction is {0: xxx, 1 :xiaobug}

rpoplpush key1 key2 Combine instructions to delete the rightmost element in key1 and put it into the leftmost element in key2. The same instructions include lpoprpush, etc., so I won’t repeat the introduction.
exists key1 Query whether the key1 key exists

3. Set is an unordered and non-repeating collection

instruction Features
sadd key1 "xiaobug"

Add a value "xiaobug" to the key key1. If key does not exist, create a key with key1 and add a value with xiaobug

smembers key1

Query all values ​​in key1 key

srandmember key1 1 Find out the specified number of elements in the key key1. If 1 or not written, it defaults to one, 2 means two, 3 means three... (Note: Because set is an unordered set, the number of elements found each time The value will not be fixed either)
sismember key1 "xiaobug" Query whether a certain value exists in key key1: "xiaobug"
scard key1 Get the data length in key key1, similar to length
srem key1 "xiaobug" In the delete key key1, the value is equal to the value of "xiaobug"
pop key1 In key key1, randomly delete an element
smove key1 key2 "xiaobug" Move the value "xiaobug" specified in key1 to key2
sdiff key1 key2

Focusing on the key key1, query all values ​​that do not exist in the key key2

sinter key1 key2 Query the intersection between key key1 and key key2
sunion key1 key2 Query the union between key key1 and key key2

4. hash hash

instruction Features
hset key1 mapkey1 "xiaobug"

Isn’t it strange why there is an extra mapkey1 here? In fact, it can be understood as map<key1,map<mapkey1,value1>>, so you can understand it. It is equivalent to putting another map into a map, and the following map The middle key is mapkey1, and the value is "xiaobug". I won't introduce this again later!

hmset key1 mapkey1 "xiao" mapkey2 "bug" Add multiple values ​​at once, same as above.
hget key1 mapkey1

Query the key1 key, the map key is the value of mapkey1

hmget key1 mapkey1 mapkey2 Querying multiple values ​​is the same as above
hgetall key1 Query all key-value pairs in key key1 (note: both keys and values ​​will be returned)
hkeys key1 Query the keys of all key-value pairs in key key1
whale key1 Query the values ​​of all key-value pairs in key key1
hdel key1 mapkey1 Delete the key-value pair named mapkey1 in key key1
hlen key1 Query the data length of key key1, similar to length
hexists key1 mapkey1 Determine whether the key-value pair mapkey1 exists in key key1
hincrby key1 mapkey1 10 Given a key named key1, the value of its key-value pair key mapkey1 is incremented by 10. (Note: Both values ​​can only be integers)
hdecrby key1 mapkey1 10 Given a key named key1, the value of its key-value pair key mapkey1 is decremented by 10. (Note: Both values ​​can only be integers)
hsetnx key1 mapkey1  "xiaobug" First determine whether the key-value pair mapkey1 in key key1 exists. If it does not exist, create the key mapkey1. If it exists, creation is not allowed.

5. zset ordered set

instruction Features

zadd key1 number1 "xiaobug"

zadd key1 1 "xiaobug"

Zset is an ordered set. It has the attribute number1, and it is also sorted according to the size of this value.

Add a value "xiaobug" to the key key1. If key does not exist, create a key with key1 and add a value with xiaobug

zrange key1 0 -1 Query the specified number of values ​​in key key1, 0 -1 means query all values.
zrangebyscore key1 -inf +inf

Query all data, sort from small to large, -inf means negative infinity, +inf means positive infinity, you can also specify a range and replace positive and negative infinity with a numerical value.

zrangebyscore key1 10 100  withscores Query the value of number greater than 10 and less than 100, and display the number and value in positive order
zrevrange key1 100 10 Like the above, this one is a flashback
zrem key1 "xiaobug" Delete an element with a specified value
zcard key1 Query the number of elements in the collection, similar to length
zcount key1 1 10 Are you familiar with this command? It counts the amount of data within a specified range. Here is the count of numbers greater than 1 and less than 10.

6. geospatial geographical location

geoadd key1 j1 w1 n1

geoadd key1 106.123 35.123 xiaobug

Insert a geographical location, if it does not exist, add it, key1 key, j1 longitude, w1 dimension, n1 name

geopos key1 n1

geopos key1 xiaobug

Query the geographical location named n1 in key1

geodist key1 n1 n2 d1

Geodist Key1 Xiaoming Km

Query the distance between n1 position and n2 position in key1. The unit of d1 distance: m meters, km kilometers, mi miles, ft feet

georadius key1 j1 w1 s1 d1 

georadius key1 106.12 35.12 100 km

Using j1 and w1 (latitude and longitude) as dots, query all locations within the specified range, key1 key, j1 longitude, w1 dimension, s1 distance, d1 unit

georadiusbymember key1 n1 s1 d1

georadiusbymember key1 xiaobug 100 km

Using the position of the specified name in key1 as a dot, query all positions within the specified range, key1 key, n1 name, s1 distance, d1 unit

7. Statistics of hyperloglog cardinality

Note: There will be errors in this statistics, but the errors are very small. Please pay attention to the usage scenarios when using;

instruction Features

pfadd key1 value1 value2 ...

Create a key key1 with the values: value1, value2,...

pfcount key1 Count how many values ​​exist in the key key1
pfmerge key1 key2 key3

key1 = key2 + the union of the values ​​in key3 (unrepeated elements).

For example: key2 = {1, 3, 5, 7, 9, 10}, key3 = {2, 4, 6, 8, 10},

key1 is: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

8. bitmap bitmap

instruction Features

setbit key1 v1 n1

setbit key1 0 1

Create a key key1, the first value is 1, key1 key, v1 number, n1 value (can only be 0, 1 binary numbers).

Does this function feel familiar? Online - not online, checked in - not checked in, yes and no, can be used to process data with only two structures

getbit key1 v1

getbit key1 0

Query the value in key key1, query the first value in key key1 (note that it starts from position 0)
bitcount key1

Count the number of values ​​1 in key key1

6. Redis transactions

        The five basic types and three special types of instructions have almost been written. In fact, many instructions are similar, just try more;

        Now let’s talk about redis transactions again. The most important point is: redis transactions are not atomic. A single instruction of redis is atomic, but transactions are not!

        There are two kinds of errors in redis transactions:

                1. Syntax errors (similar to compilation errors in Java). This kind of error will definitely not be executed. If there is an error in one place, the others cannot be executed;

                2. Execution errors (runtime errors), this is a bit of a pitfall. An error occurs in the execution of an instruction in the middle, and the transaction will not be stopped at all. Other instructions will still run. This is a pitfall! And it doesn’t support transaction rollback! Do you have the urge to curse? Don’t panic. Let’s first introduce the basic syntax of redis transactions.

        Redis transactions are divided into three steps:

                1. Open the transaction;

                2. Instruction to join the team;

                3. Execute affairs;

instruction Features

multi

set key1 value1

set key2 value2

set key3 value3

exec

The simplest set of instructions, multi: start a transaction, the three set instructions are just the instructions we usually use, and then exec: execute the transaction (note: this has an execution order, executed from top to bottom, each line of instructions There is a carriage return)

So what should you do if you find that you made a mistake halfway through writing the transaction, or you don’t want it anymore? Just change exec to discard, so that the entire transaction will be terminated and all the instructions in it will not be executed.

        Let’s fill in the pit. First, we need to introduce a command: watch key1 (monitoring, also called optimistic locking). Its function is that if one of the values ​​​​is modified by another user when you are performing a transaction operation, then your entire Transactions will fail to commit.

instruction Features

watch key1

multi

incrby key1 10

set key2 value2

set key3 value3

exec

You only need to execute watch before starting the transaction. It will bind the current value and record it. For example: the original key1 value is 100. When you are executing the transaction, someone comes in and changes the key1 value to 200, then your transaction will fail to submit.

Returns null. At this time, you only need to give up monitoring and then execute it again (writing method below↓↓↓)

unwatch

watch key1

multi

incrby key1 10

set key2 value2

set key3 value3

exec

unwatch: give up monitoring, watch: re-monitor, multi: start transaction and continue execution

7. Spring boot integrates Redis use

        1. The fastest way to use (use default configuration)

                  ①Introduce dependencies

<!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>4.2.2</version>
</dependency>

                ② Configure application.yml file

server:
  port: 8082
spring:
  redis:
    host: xxx.xx.xx.xxx    #redis服务的ip地址
    port: 6379             #redis服务的端口号
    database: 0            #默认使用第0个数据库,可以不用设置
    password: xxxxxx       #redis密码,因为测试时用的不是安全模式,所以加了个密码,这个可写可不写

                ③ Just write the code directly

package com.bug.controller;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;

/**
 * springboot整合redis
 */
@RestController
public class RedisController {

    @Resource
    private RedisTemplate redisTemplate;

    @GetMapping("test1")
    public void test1(){
        //String类型
        redisTemplate.opsForValue().set("xiaobug1","小菜鸡");
        System.out.println(redisTemplate.opsForValue().get("xiaobug1"));
        //List类型
        redisTemplate.opsForList().leftPush("xiaobug2","小菜鸡");
        System.out.println(redisTemplate.opsForList().index("xiaobug2",0));;
        //set类型
        redisTemplate.opsForSet().add("xiaobug3","小菜鸡");
        System.out.println(redisTemplate.opsForSet().members("xiaobug3"));
        //...其他类型省略了哦
    }

}

(Note: This is not a safe mode, and pay attention to the open port: 6379. For local testing, you need to comment: bind 127.0.0.1 in the redis configuration file, or configure it to the IP you use for testing) This is the fastest and easiest method, but it is also the most inconvenient method to use!

        2. Customize the way to configure beans

                The dependencies and application.yml files are the same as above, so I won’t repeat them again. The main thing is to rewrite RedisTemplate. Of course, there are more other configurations than these. Here I only introduce how to use some basic writing methods.

package com.bug.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
 * redis配置类
 */
@Configuration
public class RedisConfig {
    /**
     * 使用自己的redisTemplate,序列化
     * @param factory RedisConnectionFactory
     * @return RedisTemplate<String,Object>
     */
    @Bean
    public RedisTemplate<String,Object> redisTemplates(RedisConnectionFactory factory){
        //所有的key使用String序列化,value使用json的序列化
        RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(factory);
        //key的序列化
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        //value的序列化
        redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<>(Object.class));
        //hash key的序列化
        redisTemplate.setHashValueSerializer(new StringRedisSerializer());
        //hash value的序列化
        redisTemplate.setHashValueSerializer(new Jackson2JsonRedisSerializer<>(Object.class));

        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
}

                It’s done! The use of controller is the same. During normal development, you can write some operations such as redisTemplate.opsForValue().set() into a tool class, which will be much more convenient. You can just call the method directly;

package com.bug.controller;

import com.bug.entity.TestExcel;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
/**
 * springboot整合redis
 */
@RequestMapping("/redis")
@RestController
public class RedisController {

    @Resource
    private RedisTemplate<Object, Object> redisTemplate;//使用默认配置类

    @Resource
    private RedisTemplate<String, Object> redisTemplates;//使用自定义的配置类
    /**
     * 最简便的使用方式,默认的配置类
     */
    @GetMapping("test1")
    public void test1(){
        //String类型
        redisTemplate.opsForValue().set("xiaobug1","小菜鸡");
        System.out.println(redisTemplate.opsForValue().get("xiaobug1"));
        //List类型
        redisTemplate.opsForList().leftPush("xiaobug2","小菜鸡");
        System.out.println(redisTemplate.opsForList().index("xiaobug2",0));
        //set类型
        redisTemplate.opsForSet().add("xiaobug3","小菜鸡");
        System.out.println(redisTemplate.opsForSet().members("xiaobug3"));
        //...其他类型省略了哦
    }
    /**
     * 使用自定义的配置类
     */
    @GetMapping("test2")
    public void test2(){

        TestExcel testExcel = new TestExcel();
        testExcel.setUserId("123");
        testExcel.setUserAge("18");
        testExcel.setUserName("小菜鸡");
        testExcel.setUserCardid("1135515451515");

        redisTemplates.opsForValue().set("testExcel",testExcel);
        System.out.println(redisTemplates.opsForValue().get("testExcel"));
    }
}

        3. Annotation method

                Annotations are commonly used, mainly three annotations:

                        @Cacheable(value = "xxx"): Mainly used in query methods. Every time a request is made, the cache will be searched first. If the data exists in the cache, the data will be returned directly. If it does not exist, query the database and put the data returned by the query into the cache (value: required - the name of the cache, you can also set a key: it can be combined with the value to form the key name in redis - you can also not write it).

                        @CachePut(value = "xxx"): Mainly used in new methods, it will add data directly to the cache, and then get the value through the specified name. The parameters are the same as above.

                        @CacheEvict(value = "xxx", beforeInvocation = true): Delete cache, mainly used as a method of modification and deletion (allEntries: clear all caches after method call, beforeInvocation: clear cache before method execution).

                Example: The dependencies, application.yml, and bean configuration are the same as above, so they will not be repeated.

    /**
     * 使用注解的方式
     */
    @Cacheable(value = "getWxConfig")
    @GetMapping("/getWxConfig")
    public WxConfig getWxConfig(){

        //写好的数据库查询方法,这个方法就不讲了,所有的查询都可以使用的
        List<WxConfig> list = wxConfigService.queryWxConfig();

        return list.get(0);
    }

        When we're done, we won't write examples for the other two annotations, just add them directly to the method.

8. How to use Redis in other old frameworks

        Although the current technology updates very quickly, there are still many companies using old frameworks, especially in some old projects due to the increase in the number of users, redis needs to be used.

        here we go! here we go! Use native jedis! (For convenience, just use the main method here. It would be too troublesome to build another old framework.)

1. The first step is to introduce the jedis package. If you are not using maven, it is the same to directly import the jar package.

<!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>4.2.2</version>
</dependency>

2. Create a jedis object and connect to redis (note: this is not a safe mode and no password is used)

//注意:采用jedis直连的方式是线程不安全的,要注意哦!
public static void main(String[] args) {
        Jedis jedis = new Jedis("xxx.xx.xx.xxxip地址",6379);
        //String类型
        System.out.println(jedis.set("xiaobug1","小菜鸡"));
        System.out.println(jedis.get("xiaobug1"));
        //list类型
        System.out.println(jedis.lpush("xiaobug2","小菜鸡"));
        System.out.println(jedis.lindex("xiaobug2",0));
        //set类型
        System.out.println(jedis.sadd("xiaobug3","小菜鸡"));
        System.out.println(jedis.smembers("xiaobug3"));
        //...其他类型省略了

        //关闭连接
        jedis.close();
    }

In fact, it’s already finished, let’s make it simple! Have you ever discovered a very magical phenomenon? The method names in Jedis are exactly the same as the native instructions? You guessed it right, they are exactly the same.


Afterword

        I originally planned to write a single service and a cluster together, but it took too much time, and the article is too long. This article only introduces the single service, and other cluster construction, master-slave replication, sentry mode, cache breakdown, and penetration. , avalanche, etc. will be written in the next article. I write incessantly, and I can only take some time to rest. I have been writing this article for more than a month, and I am so tired. All my articles can be forwarded, but you need to bring a link to my original article when forwarding. All these drops are the baby's sweat. The baby is feeling bitter, but the baby doesn't say anything.

Guess you like

Origin blog.csdn.net/xiaobug_zs/article/details/123923121