Micro Service Architecture - Analysis of Redis actual combat principle - 072: Redis environment construction and data structure principle

1. Introduction to redis advanced course

Redis actual combat principle core technical points:
1. Comparison between redis and other caching frameworks
2. Install linux/windows in redis environment
3. Redis data type and thread model
4. Redis persistence mechanism RDB and AOF
5. Redis queue support and transaction
6. Implementation scheme of redis cache elimination strategy
7. Highly available mechanism of redis
8 Redis application scenarios and Solutions

Course content:
1.Redis thread model
2. Five basic data types of redis
3. Installing Redis in Linux Environment
4. Spring boot Redis implements object operations

2 Redis distributed cache and local cache

Basic introduction to Redis caching framework
Redis is completely open source and free. It is a high-performance key value database, which is currently the mainstream database on the market
Redis, Memcache, TAIR (self-developed by Taobao)
Redis's official website: https://redis.io/

Memory database (nosql database), mysql, sqlserver
The relational database is stored in the hard disk, and io operation is realized for each query
Redis persistence mechanism and elimination strategy of non relational database support distributed sharing
Jvm built-in cache framework EhCache, os cache

3. What are the application scenarios of redis

Redis application scenario

  1. Generation of Token
  2. SMS verification Code
  3. Cache query data and reduce the pressure of database access
    Inconsistency between Redis and mysql data
  4. Help implement counters
  5. Distributed lock
  6. Delay operation
    Second kill rush purchase order timeout: cancel the order within 30 minutes, inventory + 1
  7. Distributed messaging middleware (publish subscribe)

4 Redis thread model IO multiplexing

Redis officially has no windows version of redis, only the linux version.
Why does Redis only have linux version but not windows version?
Redis adopts nio's io multiplexing principle, that is, one thread (single thread) maintains multiple different redis client connections, so as to improve the processing efficiency of concurrency and ensure thread safety. The bottom layer adopts epoll Technology (event callback) of linux operating system to avoid empty round robin.

5. Redis foreground startup environment installation

Installing Redis in Linux Environment

1 upload Redis Installation package for /usr
redis-5.0.6.tar.gz
2 Unzip our Redis Installation package
tar -zxvf redis-5.0.6.tar.gz
3 mkdir /usr/redis
4 cd redis-5.0.6
make install PREFIX=/usr/redis
 If an error is reported gcc Command not found
 Execution: yum -y install gcc automake autoconf libtool make
 delete redis,redis-5.0.6 Perform the above 234 operations again for the directory
5 start-up Redis cd /usr/redis/bin     ./redis-server 

6. Redis settings allow external access

Environment core configuration
Set Redis as background startup
cp /usr/redis-5.0.6/redis.conf /usr/redis/bin
cd /usr/redis/bin
vi redis.conf modify daemon yes
./redis-server ./redis.conf restart Redis
ps aux | grep 'redis'

Set Redis account password
vi redis.conf modify # requirepass foobared
requirepass 123456
Client connection:/ redis-cli
auth 123456

Set IDs to allow ip access
Turn off the firewall systemctl stop firewalld
vi redis.conf comment out # bind 127.0.0.1
The protected mode is changed to no ### to allow external access

7. Redis is divided into 16 databases

Redis is divided into 16 libraries by default
0-15, each individual library key is not allowed to be repeated, and different library keys are allowed to be repeated

8. Five data types of redis

Redis data structure
String type, Hsh type, List type, Set type, sorted sets

./redis-cli -h 192.168.206.101 -p 6379 -a 123456
String type
String is the most basic type of redis. A key corresponds to a value. Redis string can contain any data. For example, for jpg pictures or serialized objects, the Sring type is the most basic data type of redis, and one key can store 512MB at most.
Set name mayikt
Get name

Hash type
The Hash type in Redis is regarded as having < key, < key1, value > >, where the same key can have multiple < key1, value > with different key values, so this type is very suitable for storing the information of value objects. Such as Username, Password and Age. If the Hash contains few fields, this type of data will also take up very little disk space.
HMSET mayikt zhangsan 21 lisi 22 wangwu 23
HGETALL mayikt

List type
Redis list is a simple string list, sorted by insertion order. You can add an element to the head (left) or tail (right) of the list
LPUSH mayiktlist xiaoming xiaojun xiaoxiao
LRANGE mayiktlist 0 10

Redis set
Redis' Set is an unordered Set of String type. Collection members are unique, which means that duplicate data cannot appear in the collection.
The collection in Redis is realized through hash table, so the complexity of adding, deleting and searching is O(1).
SADD mayiktset mayikt mayikt02 mayikt03 mayikt03
SMEMBERS mayiktset

Redis sorted set
Redis ordered collections, like collections, are collections of string elements, and duplicate members are not allowed.
The difference is that each element is associated with a score of type double. redis sorts the members of the collection from small to large through scores.
Members of an ordered set are unique, but scores can be repeated.
ZADD mayiktsets 1 redis
ZRANGE mayiktsets 0 10 WITHSCORES

How Redis stores a java object
Just store the json type directly
Set key=user value={"userid":100,"username":yushengjun}
How does the underlying layer of XXL SSO store binary objects

9. Spring boot integrates Redis framework

Spring boot integrates Redis
Store an object in Redis and use json to serialize and deserialize

Maven dependency

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.1.RELEASE</version>
</parent>
<dependencies>
    <!-- integrate commons Tool class -->
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-lang3</artifactId>
    </dependency>
    <!-- integrate lombok frame -->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
    </dependency>
    <!-- fastjson -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.30</version>
    </dependency>
    <!-- SpringBoot-integration Web assembly -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
</dependencies>
<!-- Management dependency -->
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>Finchley.M7</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

Tool class

@Component
public class RedisUtils {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public void setString(String key, String value) {
        setString(key, value, null);
    }

    public void setString(String key, String value, Long timeOut) {
        stringRedisTemplate.opsForValue().set(key, value);
        if (timeOut != null) {
            stringRedisTemplate.expire(key, timeOut, TimeUnit.SECONDS);
        }
    }

    public String getString(String key) {
        return stringRedisTemplate.opsForValue().get(key);
    }

}

Other codes

@Data
public class UserEntity {
    private Long userId;
    private String userName;
}
@RestController
public class RedisController {

    @Autowired
    private RedisUtils redisUtils;

    @GetMapping("/addUser")
    private String addUser(UserEntity userEntity) {
        // Convert object to json
        String jsonString = JSONObject.toJSONString(userEntity);
        redisUtils.setString("userEntity", jsonString);
        return "Storage successful";
    }

    @GetMapping("/getUser")
    public UserEntity getUser(String key){
        String jsonString = redisUtils.getString(key);
        UserEntity userEntity = JSONObject.parseObject(jsonString, UserEntity.class);
        return userEntity;
    }
}
@SpringBootApplication
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class);
    }
}

Configuration file application yml

spring:
  redis:
    host: 192.168.206.101
    password: 123456
    port: 6379
    database: 1

Test results:

Tags: Java Redis

Posted by samudasu on Sun, 17 Apr 2022 17:41:52 +0930