springboot + ehcache缓存
1. 加载依赖包
<!-- 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">
<diskStore path="java.io.tmpdir" />
<defaultCache eternal="false" maxElementsInMemory="1000"
overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="0"
timeToLiveSeconds="600" memoryStoreEvictionPolicy="LRU" />
<cache
name="userCache"
maxElementsInMemory="1000"
eternal="false"
timeToIdleSeconds="300"
timeToLiveSeconds="300"
overflowToDisk="false"
memoryStoreEvictionPolicy="LRU">
<!-- 配置缓存事件监听器 replicateAsynchronously 操作是否异步,默认值为true. replicatePuts 添加操作是否同步到集群内的其他缓存,默认为true.
replicateUpdates 更新操作是否同步到集群内的其他缓存,默认为true. replicateUpdatesViaCopy 更新之后的对象是否复制到集群中的其他缓存(true);
replicateRemovals 删除操作是否同步到集群内的其他缓存,默认为true. -->
<cacheEventListenerFactory
class="net.sf.ehcache.distribution.RMICacheReplicatorFactory"
properties="
replicateAsynchronously=true,
replicatePuts=true,
replicateUpdates=true,
replicateUpdatesViaCopy=true,
replicateRemovals=true " />
<!-- 初始化缓存,以及自动设置 -->
<bootstrapCacheLoaderFactory
class="net.sf.ehcache.distribution.RMIBootstrapCacheLoaderFactory"
properties="bootstrapAsynchronously=true" />
</cache>
</ehcache>
3.在application.properties设置缓存,扫描ehcache.xml(这里就和ehcacheManager类似,创建缓存管理器)
#cache 多个用逗号分开
spring.cache.cache-names=userCache
spring.cache.jcache.config=classpath:ehcache.xml
4.同样是在application.properties文件中(为了便于查看是否是通过了数据库查询,还是通过缓存,我们需要在控制台打印,是否调用了mapper中的sql语句),所以需要,开启debug打印,并且扫描需要打印的mapper(和数据库交互,有sql语句的包)
##默认情况下,spring boot从控制台打印出来的日志级别只有ERROR, WARN 还有INFO,如果你想要 打印debug级别的日志,可以通过application.properites配置debug=true
debug=true
#
##配置logging.level.*来具体输出哪些包的日志级别
#logging.level.org.springframework.web=DEBUG
logging.level.com.lbl.mapper=DEBUG
5.mapper文件,主要是@CacheConfig(cacheNames = “userCache”)将缓存存入缓存管理器
@CacheConfig等注解详情 https://www.jb51.net/article/112849.htm 等都可百度
package com.lbl.mapper;
import com.lbl.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import java.util.List;
@Mapper
@CacheConfig(cacheNames = "userCache")
public interface UserMapper {
//获取用户信息
@Cacheable
@Select("select * from user where ID = 1")
User getUser();
@Select("select * from user")
List<User> findAll();
@Select("select count(1) from user")
Integer countItem();
}
6.controller 分页功能在前一篇说到,这里只用了getUer测试
package com.lbl.controller;
import com.lbl.entity.User;
import com.lbl.service.IUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/user")
public class UserController {
private static final Logger logger = LoggerFactory.getLogger(UserController.class);
@Autowired
private IUserService userService;
@GetMapping("/getUser")
public User getUser(){
User user = new User();
return userService.getUser(1);
}
@GetMapping("/findAll")
public List<User> findAll(){
return userService.findAll();
}
/**
* 商品分页功能(集成mybatis的分页插件pageHelper实现)
* @param currentPage :当前页数
* @param pageSize :每页显示的总记录数
* @return
*/
@RequestMapping("/findByPage")
@ResponseBody
public List<User> itemsPage(int currentPage,int pageSize){
return userService.findItemByPage(currentPage, pageSize);
}}
7.测试文件test.java
package com.lbl.sbm;
import com.lbl.entity.User;
import com.lbl.service.IUserService;
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.SpringJUnit4ClassRunner;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class SbmApplicationTests {
@Autowired
private IUserService userService;
@Test
public void contextLoads() {
User user1 = userService.getUser(1);
System.out.println("第一次"+user1);
User user2 = userService.getUser(1);
System.out.println("第二次"+user2);
}
}
8.最后就是在app文件中开启缓存就ok了 ,就可以看到 第一次查询调用了sql语句,第二次查询没有
package com.lbl.sbm;
import com.github.pagehelper.PageHelper;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import java.util.Properties;
@SpringBootApplication
// 启用缓存注解
@EnableCaching
@EntityScan("com.lbl.entity")
@MapperScan("com.lbl.mapper")
@ComponentScan(basePackages={"com.lbl.controller","com.lbl.service"})
public class SbmApplication {
public static void main(String[] args) {
SpringApplication.run(SbmApplication.class, args);
}
//分页
@Bean
public PageHelper pageHelper() {
PageHelper pageHelper = new PageHelper();
Properties p = new Properties();
p.setProperty("offsetAsPageNum", "true");
p.setProperty("rowBoundsWithCount", "true");
p.setProperty("reasonable", "true");
p.setProperty("dialect", "mysql");
p.setProperty("supportMethodsArguments", "false");
p.setProperty("pageSizeZero", "true");
pageHelper.setProperties(p);
return pageHelper;
}
}
效果如是:第一次调用了数据库,第二次就是直接在缓存中直接查询,这样可以提高效率
反之:没有// 启用缓存注解
@EnableCaching
效果如是:两次都是调用了查询数据库
9.差不多了,简单总结就是,jar包->配置缓存文件->加载配置->设定类/方法添加某个缓存->app开启@EnableCaching就差不多了