Wechat official account: an excellent invalid. If you have any questions, please leave a message in the background. I’m not listening anyway.

preface

Two months did not update the original, really ashamed. No excuse, just because you are lazy. Recently, I read “Deliberate Learning”, which talks about the relationship between learning and action. In the book, I mentioned the concept of “continuous action”, which means that we need to do something really, and do it every day to call it “continuous action”. After reading this book, I realized that I had to do something, and that was write.

Introduction of Redis

Redis is an open source, memory-based key-value data store used as a database, cache, and message broker. On the implementation side, the key-value store represents one of the largest and oldest members of the NoSQL space. Redis supports data structures such as strings, hashes, lists, sets, and ordered sets with range queries. In the Spring Data Redis framework, spring applications can be easily written by providing an abstract data store using Redis’s key value store. Non-relational database, based on memory, access data speed is not comparable to relational database Redis is a key-value database

The data type

  • String type String
  • Hash type hash
  • List type List
  • Set type set
  • Ordered set type zset

As long as we add the spring-data-Redis dependency package and configure the Redis database, SpringBoot will automatically configure a RedisTemplate for us. Using it, we can manipulate the corresponding data types in the following ways, and I will manipulate these five data types in the following field.

  • redisTemplate.opsForValue(); // Operation string
  • redisTemplate.opsForHash(); / / the hash operation
  • redisTemplate.opsForList(); / / the list to operate
  • redisTemplate.opsForSet(); / / set operation
  • redisTemplate.opsForZSet(); // set in order

The development environment

  • SpringBoot 2.1.6 RELEASE
  • Spring – data – redis 2.1.9 RELEASE
  • Redis 3.2
  • IDEA
  • JDK8
  • mysql

How to install Redis is not described here, please search the engine to solve.

Pom depends on

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <! -- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.58</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
</dependencies>
Copy the code

The configuration file

spring:

  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: JDBC: mysql: / / 127.0.0.1:3306 / test? useUnicode=true&characterEncoding=utf8&serverTimezone=UTC&useSSL=true
    username: root
    password: 123456

  jpa:
    hibernate:
      ddl-auto: update   #ddl-auto: set to create to re-create the table each time
    show-sql: true

  redis:
    host: localhost
    port: 6379
    # Redis database index (default 0)
    database: 1
    jedis:
      pool:
        # Maximum number of connections in the pool
        max-active: 8
        Minimum idle connection
        min-idle: 0
        # Maximum blocking wait time. A negative value indicates no limit
        max-wait: - 1ms
        # Maximum free connection
        max-idle: 8
    Connection timeout (ms)
    timeout: 20ms
    # Do not write without password
    # password:
Copy the code

Why is it garbled?

    /** * Add string */
    @Test
    public void setString(a){
        redisTemplate.opsForValue().set(USERKEY,"nasus");
        redisTemplate.opsForValue().set(AGEKEY,24);
        redisTemplate.opsForValue().set(CITYKEY,"Qingyuan");
    }
Copy the code

The first is to add string data. It runs as follows:

How to solve garbled characters

We can see that the inserted data is garbled because SpringBoot automatically configures the RedisTemplate without setting the serialization of the key and value when the data is read. Therefore, we need to write our own RedisTemplate and set the serialization method of key and value so that we can operate Redis normally. As follows:

@Configuration
public class RedisConfig {

    private final RedisTemplate redisTemplate;

    @Autowired
    public RedisConfig(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Bean
    @SuppressWarnings("unchecked")
    public RedisTemplate<String, Object> redisTemplate(a) {
        RedisSerializer<String> stringSerializer = new StringRedisSerializer();
        //RedisSerializer<Object> jsonString = new GenericToStringSerializer<>(Object.class);
        RedisSerializer<Object> jsonString = new FastJsonRedisSerializer<>(Object.class);
        // String keys and hash keys are serialized as strings
        redisTemplate.setKeySerializer(stringSerializer);
        redisTemplate.setHashKeySerializer(stringSerializer);
        // Values are serialized using Fastjson
        redisTemplate.setValueSerializer(jsonString);
        redisTemplate.setHashValueSerializer(jsonString);
        returnredisTemplate; }}Copy the code

At this point, run the above unit test again, and the results are fine.

Operating the List

    /** * add and get LIST */
    @Test
    public void setList(a){
        List<Student> students = studentService.findStudentList();
        log.info("students size = {}", students.size());
        // Loop to add values left to studentList
        students.forEach(value->redisTemplate.opsForList().leftPush(LISTKEY,value));
        // Add a value to the right of studentList
        Student student = new Student();
        student.setId(10);
        student.setAge(24);
        student.setName("rightPush");
        redisTemplate.opsForList().rightPush(LISTKEY,student);
        / / get the value
        log.info("studentList->{}",redisTemplate.opsForList().range(LISTKEY,0.10));
    }
Copy the code

Here we need to mention the difference between leftpush and rightpush. The former is to add an element to the head of the list corresponding to the key. The element with the largest subscript in the list is the first element in the list. The latter adds elements to the end of the list corresponding to the key, which is exactly the opposite.

Get the value, the code here is 0 to 10 rows of data, the console prints the result:

[{"name":"Good"."id":9."age":22}, {"name":"Feng Mou Hua"."id":8."age":25}, {"name":A Certain city of Blue."id":7."age":25}, {"name":"Good"."id":6."age":22}, {"name":"Feng Mou Hua"."id":5."age":25}, {"name":A Certain city of Blue."id":4."age":25}, {"name":"Feng Mou Hua"."id":3."age":25}, {"name":A Certain city of Blue."id":2."age":25}, {"name":"Basket case"."id":1."age":22}, {"name":"rightPush"."id":10."age":24}]
Copy the code

Add List result:

Note that the id values in lines 1 through 9 are exactly the opposite, whereas the normal values in the mysql data are as follows:

Operation of the set

/** * add and obtain Set */ @test public voidsetAndGetSet(){
        List<String> usernameList = new ArrayList<>();
        usernameList.add("nasus");
        usernameList.add("nasus");
        usernameList.add("A good loser."); // loop to add the value usernamelist.foreach (value-> redistemplate.opsForset ().add(SETKEY,value)); log.info("Remove usernameSet - > {}",redisTemplate.opsForSet().members(SETKEY)); } /** * delete Set */ @test public voiddelSet(){
        redisTemplate.opsForSet().remove(SETKEY,"nasus");
    }
Copy the code

Redis’s set data structure, like Java’s HashSet data structure, is unordered and non-repetitive. So I added two nasUS strings in my code, but I only added one nasus. The results are as follows:

The hash operation

The first key is the redis key, and the second key is the hashkey for each item.

/ * * * addedhash
     */
    @Test
    public void setHash(){ List<Student> students = studentService.findStudentList(); / / addfor(Student student : students){ redisTemplate.opsForHash().put(HASHKEY, student.getId().toString(), student); }} /** * deletehash
     */
    @Test
    public void delHash(){ Student student = studentService.findStudentById(0); / / delete redisTemplate. OpsForHash (). The delete (HASHKEY, JSON. ToJSONString (student)); } /** * get Hash */ @test public voidgetHash(){
        List<Student> students = redisTemplate.opsForHash().values(HASHKEY);
        log.info("values = {}", students);
    }
Copy the code

Result of adding hash:

Get the hash operation result:

The source address

Github.com/turoDog/Dem…

Recommended reading

SpringBoot | automatic configuration principle

After the language

If this article is of any help to you, please help to read it. Your good looks are my motivation to keep writing. In addition, after paying attention to send 1024 can receive free learning materials.

For more information, see this article: Python, C++, Java, Linux, Go, front-end, algorithm sharing