Spring Boot整合ehcache

1.pom文件引入

<!-- caching -->
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
   <groupId>net.sf.ehcache</groupId>
   <artifactId>ehcache</artifactId>
</dependency>

2.新建ehcache.xml 文件

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">
    <cache name="contentsCache"
           eternal="false"
           maxEntriesLocalHeap="0"
           timeToIdleSeconds="200"/>
</ehcache>

 3.yml配置

server:
  port: 80
spring:
# 缓存配置
  cache:
    type: ehcache
    ehcache:
      config: classpath:ehcache.xml

4.使用Cacheable

启动类开启缓存@EnableCaching

import com.javasvip.model.vo.TContents;
import org.apache.ibatis.annotations.Select;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;

import java.util.List;
@CacheConfig(cacheNames = "contentsCache")
public interface TContentsMapper {
    @Select("SELECT * FROM t_contents where 1 = 1 --")
    @Cacheable
    List<TContents> findTContentsList();
}

5.启动加入缓存

import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import javax.sql.DataSource;
import java.util.concurrent.Executor;

@SpringBootApplication
@EnableCaching
public class BlogApplication {
    public static void main(String[] args) {
        SpringApplication.run(BlogApplication.class, args);
    }
}

6.测试

(1)第一次请求时长

(2)第二次请求时长

猜你喜欢

转载自blog.csdn.net/zhaolinxuan1/article/details/82897929