Chapter 50: New features of SpringBoot 2.0 - the simplest redis cache integration so far

Since the SpringBootupgrade to the version, it is simpler to 2.0integrate as a cache. We only need to configure the relevant link information and use annotations to enable the cache, so that we can directly use the cache-related content in the project.RedisRedis@EnableCaching

Since I have been developing the company's persistent encapsulation framework recently, the time for writing articles is relatively small, please forgive me, but will continue to update SpringBootand SpringCloudother series of articles, so stay tuned! ! !

Objectives of this chapter

Based on SpringBoot2the completion of quick integration Reidsas a project cache, and explain some common configurations of cache.

SpringBoot enterprise-level core technology learning topic

Topic Topic name Thematic description
001 Spring Boot core technology Explain some core components of SpringBoot at the enterprise level
002 Spring Boot core technology chapter source code Each article in the Spring Boot core technology brief book corresponds to the source code of the code cloud
003 Spring Cloud core technology Comprehensive explanation of the core technologies of Spring Cloud
004 Spring Cloud core technology chapter source code Each article in the Spring Cloud core technology brief book corresponds to the source code
005 QueryDSL core technology Comprehensively explain the core technology of QueryDSL and integrate SpringDataJPA based on SpringBoot
006 SpringDataJPA core technology Comprehensive explanation of the core technology of Spring Data JPA

Build the project

If there is no local Redisenvironment before, please visit Chapter 16: Using Redis as the SpringBoot Project Data Cache article to read the configuration. Next,
let 's create a new SpringBootproject and add the dependencies used by this site. The pom.xmlconfiguration file is as follows:

...省略部分配置
<dependencies>
        <!--spring data jpa依赖添加-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <!--redis依赖添加-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <!--web相关依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--数据库依赖添加-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!--druid依赖添加-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.8</version>
        </dependency>
        <!--lombok依赖添加-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.44</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!--性能测试依赖-->
        <dependency>
            <groupId>org.databene</groupId>
            <artifactId>contiperf</artifactId>
            <version>2.3.4</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>javax.xml.bind</groupId>
            <artifactId>jaxb-api</artifactId>
            <version>2.3.0</version>
        </dependency>
    </dependencies>
...省略部分配置

In the dependencies of this chapter, we have added contiperfperformance testing tools to test the performance differences of reading from the database and the cache respectively.

Configure Redis information

I prefer to use the ymlfile method for configuration. First, delete the application.propertiesfile automatically created by the previous project, create a new application.ymlconfiguration file named, and add Redisthe relevant configuration information to the application.ymlfile, as shown below:

spring:
  application:
    name: spring-boot-redis
  jpa:
    database: mysql
    show-sql: true
  datasource:
    druid:
      username: root
      password: 123456
      url: jdbc:mysql://localhost:3306/test
  # 配置Redis的连接密码
  redis:
    password: hengyuboy

Since Redisthere are many default configurations, localhoston the default connection Redis, we only need to configure the password of the connection here, and the others use the default configuration.

enable cache

We find the created XxxApplicationentry program class, add an @EnableCachingannotation to the class to complete the opening of the cache, as shown below:

/**
 * spring-boot-redis集成项目启动类入口
 *
 * @author yuqiyu
 * @EnableCaching 注解配置启用缓存,自动配置配置文件的配置信息进行条件注入缓存所需实例
 */
@SpringBootApplication
@EnableCaching
public class SpringBootRedisApplication {
}

test

Now that our cache has been configured, is it much simpler than the previous SpringBoot1.x.xversion? Of course, if you have some additional custom configurations, it can be easily integrated.
The data reading we use in this chapter is SpringDataJPA, if you have not used it before SpringDataJPA, please visit Chapter 13: SpringBoot Actual SpringDataJPA to read and learn.

test add cache

Let's first create a query method to complete a simple data cache, the method is as follows:

    /**
     * 查询全部用户
     *
     * @return
     */
    @Cacheable(cacheNames = "user.service.all")
    public List<TestUserEntity> findAll() {
        return userRepository.findAll();
    }

Next, write a simple unit test. We directly use the test class created when creating the project and add a test method to the test class, as shown below:

    /**
     * 测试全部缓存
     */
    @Test
    public void findAll() {
        userService.findAll();
    }

When we start the findAlltest method for the first time, we can see the console output SQLas follows:

Hibernate: select testuseren0_.ui_id as ui_id1_0_, testuseren0_.ui_age as ui_age2_0_, testuseren0_.ui_name as ui_name3_0_, testuseren0_.ui_password as ui_passw4_0_ from test_user_info testuseren0_

The data this time was queried from the database. Next, we execute the findAllmethod see the console. At this time, we did not see the output, SQLwhich proves that the data this time was Redisread from the cache.

Performance Testing

We pom.xmlhave added the performance test dependency in the configuration file contiperf, so let's Redistest 数据库the performance difference between reading data from within and reading output within.

    @Rule
    public ContiPerfRule i = new ContiPerfRule();

    /**
     * 性能测试
     * 10万次查询,100个线程同时操作findAll方法
     */
    @Test
    @PerfTest(invocations = 100000, threads = 100)
    public void contextLoads() {
        userService.findAll();
    }

Our test is to query 10万times, and start 100a thread to complete this test method. Let's first test the performance of using the cache, as shown in the following figure:
Redis 100,000 performance test
This is contiperfthe data statistics generated by the execution. When we run the performance test method, contiperfit will be Automatically generate one under the target->contiperf-reportfollowing index.htmlto count the status of this execution.
When we use the Rediscache, it takes a total of time 23秒. Let's comment out the @Cacheable(cacheNames = "user.service.all")annotation and execute the performance test method again.

When we run the test, we can see that the console query SQLis continuously output, which also proves that our data is obtained directly from the database. The test results are shown in the following figure:
Database 100,000 performance test
From the above figure, we can see that the total consumption Time: 43秒, the effect is already obvious, of course, this is a local simulation test, if the reading is on a server with large concurrent and high IO reading, the gap will be even greater.

Summarize

This chapter mainly explains SpringBoot2.0how to quickly integrate versions Redis.

第一步:添加spring-boot-starter-data-redis依赖
第二步:配置@EnableCaching开启缓存
第三步:在application.yml内配置Redis相关的信息
第四步:配置@Cacheable注解完成数据缓存

The source code of this chapter has been uploaded to the code cloud:
SpringBoot supporting source code address: https://gitee.com/hengboy/spring-boot-chapter
SpringCloud supporting source code address: https://gitee.com/hengboy/spring-cloud-chapter
SpringBoot related For the series of articles, please visit: Catalog: SpringBoot Learning Catalogue
QueryDSL-related series of articles, please visit: QueryDSL General Query Framework Learning Catalogue
SpringDataJPA-related series of articles, please visit: Catalog: SpringDataJPA Learning Catalogue , thank you for reading!
Welcome to join the QQ technical exchange group and make progress together.
QQ technical exchange group

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324847667&siteId=291194637