logo-cover-spring boot 2.0 Redis整合_spring boot 2.0 集成Redis实现缓存框架(一)

一.Spring Boot 2.0 Redis整合环境准备

  • idea(或者你自己喜欢的IDE工具)
  • maven3(idea已集成其他IDE工具自行根据情况处理)
  • Redis服务(我这里下载的Windows版本测试用)

二.Spring Boot 2.0 Redis整合项目创建

这里创建的是一个基于最新Spring Boot 2.0.3的项目。然后添加了web、cache、spring data redis等模块,具体的依赖如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>demo-springboot2-redis</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>demo-springboot2-redis</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

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

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

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>


首先在spring boot 2.0的application.properties配置文件中配置Redis基础信息

######################Redis 配置 开始################################
# Redis数据库分片索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=localhost
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=
######################Redis 结束################################


在Spring Boot 2.0的启动类上添加启用缓存的注解@EnableCaching,添加后如下:

package com.example.demospringboot2redis;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@SpringBootApplication
@EnableCaching
public class DemoSpringboot2RedisApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoSpringboot2RedisApplication.class, args);
    }
}

一个入门的spring boot 2.0 Redis整合已经完成,是不是特别简单。接下来将写一个服务用来证明缓存已经启用

package com.example.demospringboot2redis.service;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
public class CacheTestService {
    final static Log log = LogFactory.getLog(CacheTestService.class);

    @Cacheable(value = "getData")
    public String getData() {
        System.out.println("=====看见这句话,表示你没有读取缓存数据====");
        return "当前系统时间搓" + System.currentTimeMillis();
    }

}

注意方法上的@Cacheable注解,只有添加该注解才能算用了缓存。接下来写个单元测试,如下
 

package com.example.demospringboot2redis;

import com.example.demospringboot2redis.service.CacheTestService;
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.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoSpringboot2RedisApplicationTests {

    @Autowired
    CacheTestService cacheTestService;

    @Test
    public void cacheTest() {
        for (int i=0;i<5;i++){
            System.out.println(cacheTestService.getData());
            try{
                Thread.sleep(1000);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

}

单元测试很简单,就是循环几次去取刚才服务中的方法值,运行单元测试结果如下:

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.0.3.RELEASE)

2018-06-26 09:48:25.058  INFO 2196 --- [           main] e.d.DemoSpringboot2RedisApplicationTests : Starting DemoSpringboot2RedisApplicationTests on DESKTOP-3EO1H6P with PID 2196 (started by xq in D:\workplace\idea\spring-security-oauth-master\demo-springboot2-redis)
2018-06-26 09:48:25.059  INFO 2196 --- [           main] e.d.DemoSpringboot2RedisApplicationTests : No active profile set, falling back to default profiles: default
2018-06-26 09:48:25.097  INFO 2196 --- [           main] o.s.w.c.s.GenericWebApplicationContext   : Refreshing org.springframework.web.context.support.GenericWebApplicationContext@4fcee388: startup date [Tue Jun 26 09:48:25 CST 2018]; root of context hierarchy
2018-06-26 09:48:25.745  INFO 2196 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode!
2018-06-26 09:48:26.618  INFO 2196 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-06-26 09:48:26.964  INFO 2196 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.web.context.support.GenericWebApplicationContext@4fcee388: startup date [Tue Jun 26 09:48:25 CST 2018]; root of context hierarchy
2018-06-26 09:48:27.126  INFO 2196 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2018-06-26 09:48:27.128  INFO 2196 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2018-06-26 09:48:27.166  INFO 2196 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-06-26 09:48:27.166  INFO 2196 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-06-26 09:48:27.917  INFO 2196 --- [           main] e.d.DemoSpringboot2RedisApplicationTests : Started DemoSpringboot2RedisApplicationTests in 3.186 seconds (JVM running for 4.513)
2018-06-26 09:48:28.140  INFO 2196 --- [           main] io.lettuce.core.EpollProvider            : Starting without optional epoll library
2018-06-26 09:48:28.142  INFO 2196 --- [           main] io.lettuce.core.KqueueProvider           : Starting without optional kqueue library
=====看见这句话,表示你没有读取缓存数据====
当前系统时间搓1529977708399
当前系统时间搓1529977708399
当前系统时间搓1529977708399
当前系统时间搓1529977708399
当前系统时间搓1529977708399
2018-06-26 09:48:33.442  INFO 2196 --- [       Thread-2] o.s.w.c.s.GenericWebApplicationContext   : Closing org.springframework.web.context.support.GenericWebApplicationContext@4fcee388: startup date [Tue Jun 26 09:48:25 CST 2018]; root of context hierarchy
Disconnected from the target VM, address: '127.0.0.1:60134', transport: 'socket'

Process finished with exit code 0

注意后面的日志,我们可以发现进入方法只有一次。说明spring boot 2.0 redis已经完美整合

通过上面的整合,我们不难发现spring boot 2.0配置越来越简单了。但是某些情况我们还是需要一些定制化的Redis整合配置,将会在后续发表spring boot 2.0 Redis自定义配置的整合