[Redis 1] overview of Redis basic knowledge, mars Java tutorial, baidu online disk

Keywords: Java Redis Back-end Programmer

;

(1) Is business data commonly used? What is the utilization rate?

If utilization is low, there is no need to write to the cache.

(2) Does the business have many read operations or write operations?

If there are many write operations and the database needs to be written frequently, there is no need to use cache.

(3) What is the size of business data?

If you want to store hundreds of megabytes of files, it will put a lot of pressure on the cache, which is not necessary.

After considering these issues, if you feel it necessary to use cache, use it! The reading logic using Redis as cache is shown in the following figure:

From the above figure, we can know the following two points:

(1) When reading data for the first time, reading Redis data will fail. At this time, the program will be triggered to read the database, read the data and write it to Redis

(2) When the data needs to be read for the second time or later, Redis will be read directly. After reading the data, the process will be ended, which greatly improves the speed.

It can be seen from the above analysis that the possibility of read operation is much greater than that of write operation. Therefore, it is obvious to use Redis to process the data that needs to be read frequently in daily life. At the same time, it also reduces the dependence on the database and greatly reduces the pressure on the database.

After analyzing the logic of read operation, let's look at the write operation process:

It can be seen from the process that the update or write operation requires multiple Redis operations. If the number of business data writes is much greater than the number of reads, it is not necessary to use Redis.

[](

)2. High speed reading and writing occasions

In today's Internet, there are more and more cases of high concurrency, such as tmall double 11, red envelopes, concert tickets, etc. on these occasions, thousands of requests arrive at the server at a moment or a short time. If you simply use the database for processing, it will be very slow even if it doesn't collapse, At least, the user experience is very poor, the number of users is flowing, at least the database is paralyzed and the service is down, and such occasions are not allowed!

Therefore, we need to use Redis to meet such high concurrency requirements. Let's take a look at the process of a request operation:

Let's further elaborate on this process:

(1) When a request arrives at the server, it only reads and writes the business data on Redis without any operation on the database, which can greatly improve the reading and writing speed and meet the corresponding high-speed requirements.

(2) However, these cached data still need to be persisted, that is, stored in the database. Therefore, after a request completes reading and writing in Redis, it will judge whether the high-speed reading and writing business is over. This judgment usually starts when the second kill commodity is 0 and the red envelope amount is 0. If it is not established, the database will not be operated; If it is true, the event will be triggered to write the cached data of Redis to the database in batch at one time, so as to complete the persistence work.

9, Using Redis in spring

As mentioned above, Redis cannot operate objects and can not easily convert between basic types and Java objects. However, in Spring, these problems can be solved by using RedisTemplate!

To achieve this effect, in addition to the Jedis package, you also need to introduce the Spring data redis package in Spring.

[](

)1. Configuring the JedisPoolConfig object using spring

In most cases, we will still use the connection pool, so first configure a JedisPoolConfig object with Spring:

<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">

    <!--Maximum idle-->

    <property name="maxIdle" value="50"/>

    <!--maximum connection-->

    <property name="maxTotal" value="100"/>

    <!--Maximum waiting time-->

    <property name="maxWaitMillis" value="20000"/>

</bean>

2. Configure factory model for connection pool

OK, now that we have configured the relevant properties of the connection pool, which factory is used to implement it? In Spring Data Redis, there are four factory models for us to choose from, which are:

  • JredisConnectionFactory

  • JedisConnectionFactory

  • LettuceConnectionFactory

  • SrpConnectionFactory

Here we simply configure it as JedisConnectionFactory:

<bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">

    <!--Redis Service address-->

    <property name="hostName" value="localhost"/>

    <!--Port number-->

    <property name="port" value="6379"/>

    <!--If you have a password, you need to configure the password-->

    <!--<property name="password" value="password"/>-->

    <!--Connection pool configuration-->

    <property name="poolConfig" ref="poolConfig"/>

</bean>

3. Configure RedisTemplate

Ordinary connections simply cannot store objects directly into Redis memory. We need an alternative: serializing objects (which can be simply understood as inheriting the Serializable interface). We can serialize the object and store it in Redis cache, and then deserialize the serialized object back to the object through the converter when taking it out. This completes our requirements:

RedisTemplate can help us complete this work. It will find the corresponding serializer to convert the key value of Redis:

<bean id="redisTemplate"

      class="org.springframework.data.redis.core.RedisTemplate"

      p:connection-factory-ref="connectionFactory"/>

4. Testing

First, write the POJO class that supports our test:

/**

 * @author: Su xiaonuan

 * @create: 2020-2-12

 */

public class Student implements Serializable{

 

    private String name;

    private int age;

 

    /**

     * Give this class a service class for testing

     */

    public void service() {

        System.out.println("The student's name is:" + name);

        System.out.println("Student age:" + age);

    }

 

    public String getName() {

        return name;

    }

 

    public void setName(String name) {

        this.name = name;

    }

 

    public int getAge() {

        return age;

    }

 

    public void setAge(int age) {

        this.age = age;

    }

}

Then write the test class:

@Test

public void test() {

    ApplicationContext context =

            new ClassPathXmlApplicationContext("applicationContext.xml");

    RedisTemplate redisTemplate = context.getBean(RedisTemplate.class);

    Student student = new Student();

    student.setName("I don't have three hearts");

    student.setAge(21);

    redisTemplate.opsForValue().set("student_1", student);

    Student student1 = (Student) redisTemplate.opsForValue().get("student_1");

    student1.service();

}

10, Redis is used in springboot

[](

)1. Add Redis dependency in springboot

<dependency>

    <groupId>org.springframework.boot</groupId>

    <artifactId>spring-boot-starter-data-redis</artifactId>

</dependency>

2. Add configuration file application.people

# REDIS (RedisProperties)

# Redis database index (0 by default)

spring.redis.database=0

# Redis server address

spring.redis.host=localhost

# Redis server connection port

spring.redis.port=6379

# Redis server connection password (blank by default)

spring.redis.password=

# Maximum number of connections in the connection pool (negative value indicates no limit)

spring.redis.pool.max-active=8

# Maximum blocking wait time of connection pool (negative value indicates no limit)

spring.redis.pool.max-wait=-1

# Maximum free connections in the connection pool

spring.redis.pool.max-idle=8

# Minimum free connections in connection pool

spring.redis.pool.min-idle=0

# Connection timeout (MS)

spring.redis.timeout=0

3. Test access

@RunWith(SpringJUnit4ClassRunner.class)

@SpringBootTest()

public class ApplicationTests {

 

    @Autowired

    private StringRedisTemplate stringRedisTemplate;

 

    @Test

    public void test() throws Exception {

 

        // Save string

        stringRedisTemplate.opsForValue().set("aaa", "111");

        Assert.assertEquals("111", stringRedisTemplate.opsForValue().get("aaa"));

 

    }

}

The above simple test case demonstrates how to read and write Redis through the automatically configured StringRedisTemplate object. From the naming of the object, it can be noted that the String type is supported. Originally, it was redistemplate < K, V > interface. StringRedisTemplate is equivalent to the implementation of redistemplate < String, String >.

4. Storage object

This step is the same as using Spring above. You only need to implement the Serializable interface of the POJO class. I'll post the test code here:

@RunWith(SpringJUnit4ClassRunner.class)

@SpringBootTest()

public class ApplicationTests {

 

    @Autowired

    private RedisTemplate redisTemplate;

 

    @Test

    public void test() throws Exception {

 

        User user = new User();

        user.setName("I don't have three hearts");

        user.setAge(21);

 

        redisTemplate.opsForValue().set("user_1", user);

        User user1 = (User) redisTemplate.opsForValue().get("user_1");

 

        System.out.println(user1.getName());

    }

}

Posted by infini on Fri, 03 Sep 2021 23:35:06 -0700