ishowcode.eth

ishowcode.eth

区块链小白

The most detailed explanation of SpringBoot in history, hand-written with great effort.

SpringBoot Basics#

1. Introduction to SpringBoot#

1.1. What is Spring Boot#

Spring Boot is a sub-project of the Spring framework, belonging to the Spring product line along with the well-known Spring framework:

Insert image description here

Spring Boot is generally referred to as a scaffold for building applications or a convenient way to set up Spring-based projects. Its main purpose is to help developers quickly build large Spring projects while minimizing XML configuration, making it ready to use out of the box, allowing developers to focus on business rather than configuration.

1.2. Why Learn Spring Boot#

Java has often been criticized for being bulky and troublesome. The reasons for this can be summarized in two points:

Complex Configuration

Various configurations in a project are actually a drain during development, as switching between thinking about Spring feature configurations and solving business problems takes time away from writing application logic.

Chaotic Dependency Management

Managing dependencies in a project is also a thankless task. Deciding which libraries to use in a project is already headache-inducing, and you also need to know which versions of these libraries won't conflict with others, which is quite tricky. Additionally, dependency management is also a drain; adding dependencies is not writing application code. If the wrong version of a dependency is chosen, the resulting incompatibility issues will undoubtedly be a productivity killer.

But Spring Boot makes all of this a thing of the past!

Spring Boot simplifies the development of Spring-based applications, allowing you to create a standalone, production-grade Spring application with just "run". Spring Boot provides out-of-the-box settings for the Spring platform and third-party libraries (the package that holds the default configurations is called a starter), so we can get started easily. Most Spring Boot applications require very little Spring configuration.

We can create a Java application using Spring Boot and start it with java -jar, resulting in a production-grade web project.

1.3. Features of Spring Boot#

1.3.1 Characteristics of Spring Boot#

  • Provides a faster onboarding experience for Spring-based development.
  • Ready to use out of the box, with no code generation and no need for XML configuration. Default values can also be modified to meet specific needs.
  • Offers common non-functional features found in large projects, such as embedded servers, security, metrics, health checks, external configurations, etc. Spring Boot is not an enhancement of Spring's functionality but rather provides a quick way to use Spring.

2. Quick Start with Spring Boot#

Next, we will use Spring Boot to set up a web project and experience the charm of Spring Boot!

2.1 Create a Maven Project#

Use the IDEA tool to create a Maven project, which can be a regular Java project.

Insert image description here

2.2 Add Spring Boot Starter Dependencies#

At this point, many students may be confused. Earlier, we mentioned that one of the issues with traditional development is chaotic dependency management. Why do we still need to manage dependencies here? Doesn't Spring Boot help us manage them?

Don't worry; our project is not yet associated with Spring Boot. Spring Boot provides a project called spring-boot-starter-parent, which manages the versions of various commonly used dependencies (not all). Our project needs to use this project as its parent, so we don't have to worry about dependency version issues; we can simply introduce the required dependencies.

2.2.1. Add Parent Project Coordinates#

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.5.RELEASE</version>
</parent>

2.2.2. Add Web Starter#

To let Spring Boot help us with various auto-configurations, we must introduce the auto-configuration dependencies provided by Spring Boot, which we call starters. Since we are working on a web project, we will introduce the web starter by adding the following dependency in the pom.xml file:

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>

It is important to note that we did not specify version information here because the Spring Boot parent project has already managed the versions. At this point, we will find that a large number of dependencies have been added to the project. These dependencies are automatically introduced by Spring Boot based on the spring-boot-starter-web dependency, and all versions are managed, avoiding conflicts.

2.3 Write Spring Boot Main Class and Controller#

To start using Spring Boot, we need to create a main class provided by Spring Boot.

package com.summer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MySpringBootApplication {
    public static void main(String[] args) {
SpringApplication.run(MySpringBootApplication.class);
}
}

In the same package or a sub-package as the main class MySpringBootApplication, create QuickStartController.

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class QuickController {
@RequestMapping("/quick")
@ResponseBody
public String quick(){
return "Spring Boot access successful!";
}
}
The @ResponseBody annotation actually converts the Java object into JSON format data to respond to the client. If the return value is a string, it will be directly written to the client.

2.4 Start Testing#

Execute the main method of the Spring Boot main class, and the console will print logs as follows:

Insert image description here

Insert image description here

From the logs, we can see that Tomcat started on port(s): 8080 (http) with context path ''. Tomcat has started, listening on port 8080, and the virtual name of the web application is empty. Open a browser and access the URL: http://localhost:8080/quick

2.5 Spring Boot Project Hot Deployment#

In development, we often modify classes, pages, and other resources repeatedly. Each modification requires a restart to take effect, which is cumbersome and wastes a lot of time. We can achieve hot deployment, allowing changes to take effect without restarting, by adding the following configuration in pom.xml.

<!-- Hot deployment configuration -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>

Note: Reasons for Spring Boot hot deployment failure in IDEA
If this situation occurs, it is not a hot deployment configuration issue. The root cause is that IntelliJ IDEA does not automatically compile by default, and you need to set up automatic compilation in IDEA as follows:

Insert image description here

Then press Shift+Ctrl+Alt+/ and select Registry.

Insert image description here

2.6 Quickly Create a Spring Boot Project with IDEA#

The pom.xml of the Spring Boot project quickly created by IDEA already imports the coordinates of the web starter dependency we selected.

Insert image description here

You can create a controller for access using the quick start method, which will not be elaborated on here.

3. Java Configuration Application#

In the introductory example, we can implement a Spring MVC project without any configuration, quickly and efficiently! However, some students may wonder what to do if we need to configure a Bean without any XML. For example, if we want to configure a database connection pool, we would have previously configured it like this:

<bean class="com.alibaba.druid.pool.DruidDataSource" id="dataSource">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>

3.1. History of Spring Configuration#

In fact, starting from Spring 3.0, the Spring official has already begun to recommend using Java configuration to replace traditional XML configuration. Let's review the history of Spring:

  • Spring 1.0 Era
    At this time, JDK 1.5 had just come out, and annotation development was not yet prevalent, so all Spring configurations were in XML format. Imagine all beans configured in XML; it's quite terrifying, and we feel for the programmers of that time.

  • Spring 2.0 Era
    Spring introduced annotation development, but it was not yet perfect, so it did not completely replace XML. Programmers often combined XML and annotations, which seems to be the way we used to do it.

  • Spring 3.0 and Later
    After 3.0, Spring's annotations became very mature, so Spring recommended that everyone use complete Java configuration to replace the previous XML. However, it seems that this was not widely promoted in China. Only when Spring Boot arrived did people slowly realize the elegance of Java configuration.

  • There is an old saying: Embrace change, embrace the future. So we should also follow the trend of the times and learn the ways of Java configuration.

3.2. Trying Java Configuration#

Java configuration mainly relies on Java classes and some annotations. Commonly used annotations include:

  • @Configuration: Declares a class as a configuration class, replacing the XML file.
  • @Bean: Declares a method, adding the method's return value to the Bean container, replacing the <bean> tag.
  • @Value: Property injection.
  • @PropertySource: Loads external property files.

Next, we will try to implement connection pool configuration using Java configuration:

  1. Add Druid connection pool dependency in pom.xml as follows:
<!-- Druid Connection Pool -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
  1. jdbc.properties
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=root
  1. Configuration Class
@Configuration
@PropertySource("classpath:jdbc.properties")
public class JdbcConfig {
@Value("${jdbc.url}")
String url;
@Value("${jdbc.driverClassName}")
String driverClassName;
@Value("${jdbc.username}")
String username;
@Value("${jdbc.password}")
String password;
@Bean
public DataSource dataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName(driverClassName);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
return dataSource;
}
}
  • Explanation:
  • @Configuration: Declares that JdbcConfig is a configuration class.
  • @PropertySource: Specifies the path of the property file as classpath:jdbc.properties.
  • The @Value annotation is used to inject values into properties.
  • The @Bean annotation declares the dataSource() method as a method for registering a Bean, and Spring will automatically call this method to add its return value to the Spring container.
    Then we can inject DataSource anywhere using @Autowired!
  1. Testing
@Controller
public class QuickController {
@Autowired
private DataSource dataSource;
@RequestMapping("/quick")
@ResponseBody
public String hello() {
System.out.println("dataSource = " + dataSource);
return "hello, spring boot!";
}
}

3.3. Property Injection in Spring Boot#

In the above example, we experimented with the Java configuration method. However, property injection used the @Value annotation. While this method is feasible, it is not powerful enough because it can only inject basic type values.

In Spring Boot, a new property injection method is provided that supports injection of various Java basic data types and complex types. The name of the property file has changed; the default file name must be:

application.properties or application.yml

@ConfigurationProperties(prefix ="jdbc")
public class JdbcProperties {
private String driverClassName;
private String url;
private String username;
private String password;
// ... getters and setters
}
  • The @ConfigurationProperties annotation on the class declares it as a property reading class.
  • prefix="jdbc" reads values from the property file with the prefix jdbc.
  • Define each property in the class, and the names must match the parts after jdbc. in the property file.
  • Note that we did not specify the property file's address here, so we need to rename jdbc.properties to application.properties, which is the default property file name read by Spring Boot.

Note: If the following prompt appears, the project can still run:

Insert image description here

To remove the above prompt, you can add the following dependency in pom.xml:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>

Elegant Injection

@Configuration
@EnableConfigurationProperties(JdbcProperties.class)
public class JdbcConfig {
@Bean
public DataSource dataSource(JdbcProperties jdbc) {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setUrl(jdbc.getUrl());
dataSource.setDriverClassName(jdbc.getDriverClassName());
dataSource.setUsername(jdbc.getUsername());
dataSource.setPassword(jdbc.getPassword());
return dataSource;
}
}

More Elegant Injection
In fact, if a set of properties is only needed by one Bean, we do not need to inject it into a class (JdbcProperties, removing all annotations from that class). Instead, we can declare it directly where needed. Modify the JdbcConfig class as follows:

@Configuration
public class JdbcConfig {
@Bean
@ConfigurationProperties(prefix = "jdbc")
public DataSource dataSource() {
return new DruidDataSource();
}
}

3.4 Yaml Configuration Files#

Configuration files can also use the .yml or .yaml suffix, such as application.yml or application.yaml. The YAML configuration file has the same functionality and purpose as the properties configuration file; the way to read it in the project does not change.

Characteristics of YAML configuration files:

  1. Displays configuration items in a tree-like hierarchical structure.
  2. If configuration items have relationships, they need to be indented two spaces.
  3. If configuration items have values, they need to be followed by a space after the :.

Basic format:

jdbc:
  driverClassName: com.mysql.jdbc.Driver
  url: jdbc:mysql://localhost:3306/kw
  username: root
  password: root

Modify application.properties to application.yml for testing.

4. Analysis of Automatic Configuration Principles#

After using Spring Boot, developing a web project integrated with Spring MVC becomes incredibly simple, as all the complicated configurations disappear. How is this achieved?

The magic begins with our main function, so let's take another look at the startup class:
Hold down Ctrl and click to view the annotation @SpringBootApplication on the startup class MySpringBootApplication.

// Create the entry point for the Spring Boot project
// Automatically scans the package where the current class is located and its sub-packages
@SpringBootApplication
public class MySpringBootApplication {
public static void main(String[] args) {
// Run the Spring Boot application
SpringApplication.run(MySpringBootApplication.class, args);
}
}

The source code of the annotation @SpringBootApplication:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = {
@Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {
@AliasFor(annotation = EnableAutoConfiguration.class)
Class<?>[] exclude() default {};
    ... ... ...
}
  • The key annotations here are three:
  • @SpringBootConfiguration: Equivalent to @Configuration, indicating that this class is a Spring configuration class.
  • @EnableAutoConfiguration: Enables Spring Boot's auto-configuration feature.
  • Hold down Ctrl and click to view the annotation @EnableAutoConfiguration.
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {
... ... ...
}

The role of @EnableAutoConfiguration is to read the auto-configuration configuration information from the META-INF/spring.factories file.

Insert image description here

The configuration information related to auto-configuration in the spring.factories file is as follows:

Insert image description here

The above configuration file contains a large number of class names ending with AutoConfiguration, which are classes that contain auto-configuration information. SpringApplication retrieves these class names and loads them.

Let's analyze the source code of ServletWebServerFactoryAutoConfiguration as an example:

@Configuration
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)
@ConditionalOnClass(ServletRequest.class)
@ConditionalOnWebApplication(type = Type.SERVLET)
@EnableConfigurationProperties(ServerProperties.class)
@Import({ ServletWebServerFactoryAutoConfiguration.BeanPostProcessorsRegistrar.class,
ServletWebServerFactoryConfiguration.EmbeddedTomcat.class,
ServletWebServerFactoryConfiguration.EmbeddedJetty.class,
ServletWebServerFactoryConfiguration.EmbeddedUndertow.class })
public class ServletWebServerFactoryAutoConfiguration {
... ... ...
}

Among them, @EnableConfigurationProperties(ServerProperties.class) indicates loading the ServerProperties server configuration properties class, which we have used before.

Entering the ServerProperties.class source code:

@ConfigurationProperties(prefix = "server", ignoreUnknownFields = true)
public class ServerProperties {
/**
* Server HTTP port.
*/
private Integer port;
/**
* Network address to which the server should bind.
*/
private InetAddress address;
    ... ... ...
}

Here, prefix = "server" indicates that Spring Boot will map properties starting with server in the configuration file to the fields of this class. The mapping relationship is as follows:

Insert image description here

  • @ComponentScan
Configures component scanning instructions. Provides functionality similar to the <context:component-scan> tag.
Specifies the packages to scan using the basePackageClasses or basePackages attributes. If these attributes are not specified, scanning will start from the package where the class declaring this annotation is located, scanning that package and its sub-packages.

Thus, the class declared with the @SpringBootApplication annotation is the main class where the main function is located, so the scanned package is that class's package and its sub-packages. Therefore, the startup class is generally placed in a relatively high-level package directory.

5. Spring Boot and Integration with Other Technologies#

5.1 Integrating Spring MVC#

Although the default configuration can already use Spring MVC, we sometimes need to customize the configuration.

5.1.1. Modify the Port#

The global properties of Spring Boot indicate that the port can be configured as follows:

server:
  port: 80

5.1.2. Access Static Resources#

Now, our project is a JAR project, so there is no webapp. Where should we place our static resources?

Recalling the source code we looked at earlier, there is a class called ResourceProperties, which defines the default lookup paths for static resources.

Insert image description here

  • The default static resource paths are:
    • classpath:/META-INF/resources/
    • classpath:/resources/
    • classpath:/static/
    • classpath:/public
Note: If images do not display when accessed, you can clean the project and restart it, or create `public` and `resources` folders, then place the images in `public` or `resources`.

5.2 Integrating JDBC and Transactions#

JDBC connections and transactions are important parts of configuration in Spring. How do we handle this in Spring Boot? The answer is that we don't need to handle it; we just need to find the starter provided by Spring Boot. Add the following dependency in the pom.xml file:

<!-- Integrate JDBC and Transactions -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

Of course, don't forget the database driver. Spring Boot does not know which database we are using, so we choose MySQL. Similarly, add the following dependency in the pom.xml file:

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>

As for transactions, Spring Boot controls them using annotations, specifically the well-known @Transactional, which can be set on the corresponding class or method.

5.3 Integrating Connection Pool#

In fact, when we introduced the JDBC starter earlier, Spring Boot had already automatically introduced a connection pool for us:

Insert image description here

HikariCP is currently the fastest connection pool. Let's take a look at its comparison with c3p0:

Insert image description here

Therefore, we only need to specify the connection pool parameters. Open application.yml and modify the configuration as follows:

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
    username: root
    password: root

5.4 Spring Boot Integration with MyBatis#

Add MyBatis starter dependency
The Spring Boot official does not provide a MyBatis starter, but the MyBatis official has implemented it. Add the following dependency in the pom.xml file:

<!-- MyBatis Starter Dependency -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.2</version>
</dependency>

Add the database driver coordinates:

<!-- MySQL Connection Driver -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>

Configure application.yml, common configurations are as follows:

# MyBatis Configuration
mybatis:
  type-aliases-package: com.bailiban.domain
  mapper-locations: classpath:com/bailiban/mapper/*Mapper.xml
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

Configure Mapper Scanning
Note that we have not configured the package for scanning mapper interfaces, so we need to add the @Mapper annotation to each mapper interface for it to be recognized.

@Mapper
public interface UserMapper {
}

Alternatively, we can add the scanning package annotation on the startup class (recommended):

@SpringBootApplication
@MapperScan("com.bailiban.mapper")
public class MySpringBootApplication {
public static void main(String[] args) {
SpringApplication.run(MySpringBootApplication.class);
}
}

5.4.1 Create User Table#

Create the user table in the test database:

DROP table if EXISTS user;
CREATE TABLE `user` (
`uid` INT AUTO_INCREMENT,
`username` VARCHAR(20) DEFAULT NULL,
`password` VARCHAR(20) DEFAULT NULL,
`realname` VARCHAR(20) DEFAULT NULL,
`email` VARCHAR(30) DEFAULT NULL,
`telephone` VARCHAR(20) DEFAULT NULL,
PRIMARY KEY (`uid`)
);
INSERT INTO `user` VALUES (NULL,'wc001','888888','旺财','[email protected]','15723689921'),
(NULL,'xq001','888888','小强','[email protected]','15723689922'),
(NULL,'xb001','888888','小宝','[email protected]','15723689923');

5.4.2 Create Entity Bean#

package com.bailiban.domain;
public class User {
private int uid; // User ID
private String username; // Username
private String password; // Password
private String realname; // Real Name
private String email; // Email
private String telephone; // Phone
// Omitted setter and getter methods
}

5.4.3 Write Mapper#

@Mapper
public interface UserMapper {
public List<User> queryUserList();
}

Note: The @Mapper annotation marks this class as a MyBatis mapper interface, allowing it to be automatically scanned into the Spring context.

5.4.4 Configure Mapper Mapping File#

Add the UserMapper.xml configuration file in the src/main/resources/com/bailiban/mapper path:

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.bailiban.mapper.UserMapper">
<select id="queryUserList" resultType="user">
select * from user
</select>
</mapper>

5.4.5 Add MyBatis Information in application.yml#

# MyBatis Configuration
mybatis:
  type-aliases-package: com.bailiban.domain
  mapper-locations: classpath:com/bailiban/mapper/*Mapper.xml
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

5.4.6 Write Test Controller#

@Controller
public class MapperController {
@Autowired
private UserMapper userMapper;
@RequestMapping("/queryUser")
@ResponseBody
public List<User> queryUser(){
List<User> users = userMapper.queryUserList();
return users;
}
}

5.5 JUnit Testing#

  1. If you want to use JUnit for unit testing in a Spring Boot project, you need to add the following starter:
<!-- Unit Test Starter -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-starter-test</artifactId>
</dependency>
  1. Write a test class in the test package
    The @SpringBootTest annotation must be added to the test class.
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserServiceTest {
@Autowired
private UserService userService;
@Test
public void test1(){
List<User> users = userService.selectAll();
System.out.println(users);
}
}

5.6 Integrating Redis#

Concept: Redis is a high-performance NoSQL series non-relational database.

5.6.1 What is NoSQL#

NoSQL (NoSQL = Not Only SQL) refers to a new database concept that encompasses non-relational databases. With the rise of web 2.0 websites, traditional relational databases have struggled to cope with the demands of large-scale and high-concurrency web 2.0 dynamic websites, exposing many insurmountable issues. Non-relational databases have rapidly developed due to their inherent characteristics. The emergence of NoSQL databases aims to address the challenges posed by large-scale data collections with multiple data types, especially in big data applications.

5.6.2 Comparison of NoSQL and Relational Databases#

Advantages:

  1. Cost: NoSQL databases are simple to deploy and are mostly open-source software, avoiding the high costs associated with using Oracle, making them cheaper than relational databases.

  2. Query Speed: NoSQL databases store data in memory, while relational databases store data on disk, resulting in faster query speeds for NoSQL databases.

  3. Data Storage Formats: NoSQL supports various formats such as key-value pairs, documents, images, etc., allowing storage of basic types, objects, or collections, while relational databases only support basic types.

  4. Scalability: Relational databases have limitations due to mechanisms like joins for multi-table queries, making scalability difficult.

Disadvantages:

  1. Limited maintenance tools and resources, as NoSQL is a newer technology compared to the decade-long technology of relational databases.

  2. Lack of support for SQL, which is an industrial standard, leading to a certain learning and usage cost for users.

  3. Lack of transaction handling provided by relational databases.

Summary:
Relational databases and NoSQL databases are not opposing but complementary. Typically, relational databases are used, while NoSQL databases are employed when suitable, allowing NoSQL to compensate for the shortcomings of relational databases. Data is generally stored in relational databases, with NoSQL databases used for backup storage of relational database data.

5.6.3 Mainstream NoSQL Products#

Related Products: Tokyo Cabinet/Tyrant, Redis, Voldemort, Berkeley DB
Typical Applications: Content caching, primarily for handling high access loads of large data.
Data Model: A series of key-value pairs
Advantages: Fast querying
Disadvantages: Lack of structured data storage

Document-oriented databases
Related Products: CouchDB, MongoDB
Typical Applications: Web applications (similar to Key-Value, where Value is structured)
Data Model: A series of key-value pairs
Advantages: Less strict data structure requirements
Disadvantages: Lower query performance and lack of unified query syntax

5.6.4 What is Redis#

Redis is an open-source high-performance key-value (key-value) database developed in C language. The official test data shows that with 50 concurrent executions of 100,000 requests, the read speed is 110,000 times/s, and the write speed is 81,000 times/s. Redis provides various key-value data types to meet different storage needs in various scenarios. Currently, the key-value data types supported by Redis are:

  1. String type
  2. Hash type
  3. List type
  4. Set type
  5. Sorted set type

5.6.5 Redis Application Scenarios#

  • Caching (data queries, short connections, news content, product content, etc.)
  • Online friend lists in chat rooms
  • Task queues (flash sales, purchases, 12306, etc.)
  • Application leaderboards
  • Website visit statistics
  • Data expiration handling (can be precise to milliseconds)
  • Session separation in distributed cluster architectures

5.6.6 Integration#

Add the following dependency in the pom.xml file:

<!-- Redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

Configure the application.yml file:

spring:
  redis:
    host: localhost
    port: 6379

Test Code:

package com.summer.test;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.*;
@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisTest {
@Autowired
private RedisTemplate redisTemplate;
@Test
public void test1() {
// Save string, the most commonly used
redisTemplate.opsForValue().set("hello", "哈哈");
// Retrieve
String hello = (String) redisTemplate.opsForValue().get("hello");
System.out.println(hello);
// Save and read set
redisTemplate.opsForSet().add("s_key", "a", "b", "c");
Set set = redisTemplate.opsForSet().members("s_key");
System.out.println("set collection: " + set);
// Save and read List
List<String> list = Arrays.asList("a", "b", "c");
redisTemplate.opsForList().leftPush("l_key", list);
// Retrieve
List<String> list1 = (List<String>) redisTemplate.opsForList().leftPop("l_key");
System.out.println("list collection: " + list1);
// Save and read map collection
Map<String, String> map = new HashMap<>();
map.put("name", "旺财");
map.put("age", "18");
redisTemplate.opsForHash().putAll("h_key", map);
// Retrieve map
Map<String, String> map1 = redisTemplate.opsForHash().entries("h_key");
// Retrieve key collection
Set key_set = redisTemplate.opsForHash().keys("h_key");
// Retrieve value collection
List value_list = redisTemplate.opsForHash().values("h_key");
System.out.println("key collection: " + key_set);
System.out.println("value collection: " + value_list);
System.out.println("map collection: " + map1);
// Save sorted set
redisTemplate.opsForZSet().add("z_key", "a", 10);
redisTemplate.opsForZSet().add("z_key", "b", 20);
redisTemplate.opsForZSet().add("z_key", "c", 30);
// Retrieve
Set z_set = redisTemplate.opsForZSet().range("z_key", 0, -1);
System.out.println("sorted set: " + z_set);
}
}
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.