current position:Home>[spring boot 12] after reading this article, mybatis goes from introduction to mastery

[spring boot 12] after reading this article, mybatis goes from introduction to mastery

2022-01-26 21:35:06 m0_ fifty-four million eight hundred and sixty-one thousand fou

In order to overcome the above problems ,java web Projects usually introduce NoSQL technology , This is a memory based database , And provide some persistence function .

Redis and MongoDB Is currently the most widely used NoSQL,  And just Redis In terms of technology, , It has excellent performance , It can support more than 100000 read and write operations per second , Its performance is much better than that of database , And it also supports clustering 、. Distributed 、 Master slave synchronization and other configurations , In principle, it can be expanded infinitely , Let more data be stored in memory , What's more gratifying is that it also supports certain transactional capabilities , This ensures the high security of the data in this scenario .

3、 ... and 、Redis stay Java Web Application in

====================

Redis stay Java Web There are two main application scenarios :

  • Store data for caching

  • Where high-speed reading and writing is required

1、 Store data for caching


In the daily access to the database , The number of read operations far exceeds the number of write operations , The proportion is about  1:9  To  3:7, So it's much more possible to read than to write . When we use SQL Statement to the database for read-write operations , The database will go to the disk and retrieve the corresponding data index , It's a relatively slow process .

If you put it in Redis in , That is, put it in memory , Let the server directly read the data in memory , Then the speed will be much faster , And it will greatly reduce the pressure on the database , But using memory for data storage is also relatively expensive , Limited to cost reasons , Generally we just use Redis Store some common and main data , Such as user login information .

Generally speaking, in use Redis When it comes to storage , We need to consider... From the following aspects :

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

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

(2) This service is read operation , Or write more operations ?

If there are many write operations , Frequent need to write to database , There is no need to use caching .

(3) What is the size of the business data ?

If you want to store hundreds of megabytes of files , It will put a lot of pressure on the cache , It's not necessary .

After considering these problems , If you think it's necessary to use caching , Then use it ! Use Redis The read logic as a cache is shown in the figure below :

From the picture above, we can see the following two points :

(1) When reading data for the first time , Read Redis The data will fail , This triggers the program to read the database , Read the data out , And write Redis in

(2) When data needs to be read for the second time and later , It will read directly Redis, After reading the data, the process ends , This greatly improves the speed .

From the above analysis, we can know , Read operations are far more likely than write operations , So use Redis To handle the data that needs to be read frequently in daily life , The increase in speed is obvious , It also reduces the dependence on the database , So that the pressure of the database is greatly reduced .

The logic of read operation is analyzed , Now let's look at the write operation process :

As can be seen from the process , Update or write operations , Multiple required Redis The operation of , If the number of business data writes is much greater than the number of reads, there is no need to use Redis.

2、 High speed reading and writing occasions


In today's Internet , There are more and more high concurrency situations , For example, tmall double 11、 Grab a red envelope 、 Grab concert tickets, etc , In these cases, thousands of requests arrive at the server at a certain moment or a short time , If you simply use the database to process , Even if it doesn't collapse , It's going to be slow , If it is light, the user experience is very poor, and the number of users is running , Again, the database is paralyzed , The service outage , And such occasions are not allowed !

So we need to use Redis To cope with such a high concurrency situation , Let's first look at the flow of a request operation :

Let's elaborate on this process further :

(1) When a request arrives at the server , Just put the business data in Redis Read and write on , Without any operation on the database , This can greatly improve the speed of reading and writing , So as to meet the corresponding needs of high-speed .

(2) But these cached data still need to be persistent , It's stored in the database , So after a request operation Redis After reading and writing , Will judge whether the high-speed read-write business is over , This judgment is usually made when the second kill commodity is 0, The amount of the red envelope is 0 It was established , If not , The database will not be manipulated ; If set up , The trigger event will Redis The cached data is written to the database in batch at one time , So as to complete the work of persistence .

Four 、 stay java Use in Redis

===============

1、 add to Jedis rely on


Want to be in Java Use in Redis cache , Need to add related Jar Packet dependency , open Maven Warehouse website :https://mvnrepository.com/ , Search for Jedis:

Just import it into the project , Let's get right Redis Test the write performance of :

@Test

public void redisTester() {

Jedis jedis = new Jedis(“localhost”, 6379, 100000);

int i = 0;

try {

long start = System.currentTimeMillis();// Start milliseconds

while (true) {

long end = System.currentTimeMillis();

if (end - start >= 1000) {// When it is greater than or equal to 1000 millisecond ( amount to 1 second ) when , End operation

break;

}

i++;

jedis.set(“test” + i, i + “”);

}

} finally {// Close the connection

jedis.close();

}

// Print 1 Seconds, right Redis The number of operations

System.out.println(“redis Operations per second :” + i + “ Time ”);

}

----------- test result -----------

redis Operations per second :10734 Time

2、 Use Redis Connection pool

Same as database connection pool ,Java Redis Classes are also provided  redis.clients.jedis.JedisPool To manage us Reids Connect pool objects , And we can use  redis.clients.jedis.JedisPoolConfig To configure the connection pool , The code is as follows :

JedisPoolConfig poolConfig = new JedisPoolConfig();

// Maximum free number

poolConfig.setMaxIdle(50);

// maximum connection

poolConfig.setMaxTotal(100);

// Maximum waiting milliseconds

poolConfig.setMaxWaitMillis(20000);

// Create a connection pool using configuration

JedisPool pool = new JedisPool(poolConfig, “localhost”);

// Get a single connection from the connection pool

Jedis jedis = pool.getResource();

// If you need a password

//jedis.auth(“password”);

Redis Only six data structures can be supported  (string/hash/list/set/zset/hyperloglog) The operation of  , But in Java In, we usually focus on class objects , So in Redis Stored data structure month java Convert between objects , Such as writing some tool classes by yourself   For example, changing the role of an object , It's easy , But when it comes to many objects , Both the workload and the difficulty of the work are very big , So in general ,  In terms of operands , Use Redis It's still hard , Fortunately spring These are encapsulated and supported .

5、 ... and 、 stay spring Use in Redis

=================

It says Redis Unable to manipulate the object , Can't be used in those base types and Java Easy conversion between objects , But in Spring in , These problems can be solved by using RedisTemplate Be solved !

I want to do that , except Jedis In addition to the package, you need to Spring introduce spring-data-redis package .

1、 Use spring To configure JedisPoolConfig object


Most of the time , We'll still use connection pooling , So I used it first Spring To configure a JedisPoolConfig object :

2、 Configure the factory model for the connection pool


Okay , We have now configured the related properties of the connection pool , So what kind of factory is used to realize it ? stay Spring Data Redis There are four factory models for us to choose from , They are :

  • JredisConnectionFactory

  • JedisConnectionFactory

  • LettuceConnectionFactory

  • SrpConnectionFactory

Here we simply configure it as JedisConnectionFactory:

3、 To configure RedisTemplate


There's no way to store objects directly in a normal connection Redis In the memory , We need alternatives

《 A big factory Java Analysis of interview questions + Back end development learning notes + The latest architecture explanation video + Practical project source code handout 》

【docs.qq.com/doc/DSmxTbFJ1cmN1R2dB】 Full content open source sharing

The plan : Serialize objects ( It can be simply understood as inheritance Serializable Interface ). We can serialize the object and store it in Redis In cache , And then it goes through the converter when it's taken out , Deserialize the serialized object back to the object , That's what we asked for :

RedisTemplate Can help us finish this job , It will find the corresponding serializer to convert Redis Key value of :

<bean id=“redisTemplate”

class=“org.springframework.data.redis.core.RedisTemplate”

p:connection-factory-ref=“connectionFactory”/>

4、 test


First of all, write the software that supports our testing POJO class :

/**

  • @author: Simple little warm

  • @create: 2020-2-12

*/

public class Student implements Serializable{

private String name;

private int age;

/**

  • Give this class a service class to test

*/

public void service() {

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

System.out.println(“ The age of the students is :” + 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();

}

Running results :

copyright notice
author[m0_ fifty-four million eight hundred and sixty-one thousand fou],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/01/202201262135039065.html

Random recommended