一、springboot缓存简介

在 Spring Boot中,通过@EnableCaching注解自动化配置合适的缓存管理器(CacheManager),Spring Boot根据下面的顺序去侦测缓存提供者:
* Generic
* JCache (JSR-107)
* EhCache 2.x
* Hazelcast
* Infinispan
* Redis
* Guava
* Simple

关于 Spring Boot 的缓存机制:
高速缓存抽象不提供实际存储,并且依赖于由org.springframework.cache.Cache和org.springframework.cache.CacheManager接口实现的抽象。 Spring Boot根据实现自动配置合适的CacheManager,只要缓存支持通过@EnableCaching注释启用即可。

二、实例

1、application.properyies

server.port=8850

#cache 多个用逗号分开
spring.cache.cache-names=userCache
spring.cache.jcache.config=classpath:ehcache.xml # datasource
spring.datasource.name=ehcahcetest
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3312/ehcahcetest
spring.datasource.username=root
spring.datasource.password=123456 # mybatis
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
mybatis.config-location=classpath:mybatis/mybatis-config.xml
#mybatis.type-aliases-package=

2、springboot启动类

 @SpringBootApplication
@ComponentScan(basePackages="com.ehcache")//扫描组件
@EnableCaching
public class EhcacheTestApplication { public static void main(String[] args) {
SpringApplication.run(EhcacheTestApplication.class, args);
}
}

3、加了缓存注解的service

 @Service
public class UserService { @Autowired
private UserDao userDao; @CacheEvict(key="'user_'+#uid", value="userCache")
public void del(String uid) {
// TODO Auto-generated method stub
userDao.del(uid);
} @CachePut(key="'user_'+#user.uid", value="userCache")
public void update(User user) {
userDao.update(user);
} @Cacheable(key="'user_'+#uid",value="userCache")
public User getUserById(String uid){
System.err.println("缓存里没有"+uid+",所以这边没有走缓存,从数据库拿数据");
return userDao.findById(uid); } @CacheEvict(key="'user'",value="userCache")
public String save(User user) {
// TODO Auto-generated method stub
return userDao.save(user);
} }

4、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" /> <!-- 配置提供者 1、peerDiscovery,提供者方式,有两种方式:自动发现(automatic)、手动配置(manual) 2、rmiUrls,手动方式时提供者的地址,多个的话用|隔开 -->
<cacheManagerPeerProviderFactory
class="net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory"
properties="peerDiscovery=manual,rmiUrls=//127.0.0.1:40002/userCache" />
<!-- <cacheManagerPeerProviderFactory
class="net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory"
properties="peerDiscovery=automatic, multicastGroupAddress=230.0.0.1, multicastGroupPort=4446,timeToLive=255"/>
-->
<!-- 配置监听器 1、hostName 主机地址 2、port 端口 3、socketTimeoutMillis socket子模块的超时时间,默认是2000ms -->
<cacheManagerPeerListenerFactory
class="net.sf.ehcache.distribution.RMICacheManagerPeerListenerFactory"
properties="hostName=127.0.0.1, port=40001, socketTimeoutMillis=2000" />
<!-- <cacheManagerPeerListenerFactory
class="net.sf.ehcache.distribution.RMICacheManagerPeerListenerFactory"/> --> <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>

5、OperationController.java 测试类

 package com.ehcache.controller;

 import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController; import com.ehcache.entity.User;
import com.ehcache.factory.CacheManagerFactory;
import com.ehcache.factory.UserFactory;
import com.ehcache.service.UserService;
import com.google.gson.Gson; import net.sf.ehcache.Element; @RestController
@RequestMapping("/o")
public class OperationController { @Autowired
private UserService userService; Gson gson = new Gson(); CacheManagerFactory cmf = CacheManagerFactory.getInstance(); @RequestMapping(value = "/test", method = RequestMethod.GET)
public String test(HttpServletRequest request){ // 保存一个新用户
String uid = userService.save(UserFactory.createUser());
User user = userService.getUserById(uid);
user.setUsername("xiaoli");
userService.update(user); // 查询该用户
System.out.println(gson.toJson(user, User.class));
/*System.out.println();
// 再查询该用户
User user = userService.getUserById(uid);
System.out.println(gson.toJson(user, User.class));
System.out.println();
// 更新该用户
userService.update(user);
// 更新好了再查询该用户
System.out.println(gson.toJson(userService.getUserById(uid), User.class));
System.out.println();
// 删除该用户
userService.del(uid);
System.out.println();
// 删除好了再查询该用户
System.out.println(gson.toJson(userService.getUserById(uid), User.class));*/ // 再保存一个新用户
// String uid1 = userService.save(UserFactory.createUser()); return uid;
} @RequestMapping(value = "/test1", method = RequestMethod.GET)
public String test1(HttpServletRequest request,String key){ String res = ""; Element element = cmf.getElement("userCache", "map");
if(element == null){
Map<String, String> map = new HashMap<String, String>();
map.put(key, key);
cmf.setElement("userCache", new Element("map", map));
}else{
Map<String, String> map = (Map<String, String>) element.getValue();
res = map.get(key);
if(res == null){
map.put(key, key);
// 多次测试发现,存在同名Element是,重复put的是无法复制的,因此当遇到两个节点同步不上的时候,先remove后put。
cmf.getCache("userCache").remove("map");
cmf.setElement("userCache", new Element("map", map));
res = "0;null";
}
}
return res;
} }

springboot+mybatis+ehcache实现缓存数据的更多相关文章

  1. Shiro+springboot+mybatis+EhCache(md5+salt+散列)认证与授权-03

    从上文:Shiro+springboot+mybatis(md5+salt+散列)认证与授权-02 当每次进行刷新时,都会从数据库重新查询数据进行授权操作,这样无疑给数据库造成很大的压力,所以需要引入 ...

  2. MyBatis ehcache二级缓存

    ehcache二级缓存的开启步骤: 1.导入jar 2.在映射文件中指定用的哪个缓存 3.加一个配置文件,这个配置文件在ehcache jar包中就有 使增删改对二级缓存不刷新: 对一级缓存没有用的, ...

  3. Springboot + Mybatis + Ehcache

    最近在做一个项目,为处理并发性较差的问题,使用了Mybatis二级缓存 但在多表联合查询的情况下,Mybatis二级缓存是存在着数据脏读的问题的 两天就是在想办法解决这个数据脏读的问题 考虑到简易性. ...

  4. springboot mybatis redis 二级缓存

    前言 什么是mybatis二级缓存? 二级缓存是多个sqlsession共享的,其作用域是mapper的同一个namespace. 即,在不同的sqlsession中,相同的namespace下,相同 ...

  5. 【spring-boot】spring-boot 整合 ehcache 实现缓存机制

    方式一:老 不推荐 参考:https://www.cnblogs.com/lic309/p/4072848.html /*************************第一种   引入 ehcach ...

  6. 【spring-boot】spring-boot整合ehcache实现缓存机制

    EhCache 是一个纯Java的进程内缓存框架,具有快速.精干等特点,是Hibernate中默认的CacheProvider. ehcache提供了多种缓存策略,主要分为内存和磁盘两级,所以无需担心 ...

  7. spring-boot整合ehcache实现缓存机制

    EhCache 是一个纯Java的进程内缓存框架,具有快速.精干等特点,是Hibernate中默认的CacheProvider. ehcache提供了多种缓存策略,主要分为内存和磁盘两级,所以无需担心 ...

  8. springboot+mybatis+redis实现分布式缓存

    大家都知道springboot项目都是微服务部署,A服务和B服务分开部署,那么它们如何更新或者获取共有模块的缓存数据,或者给A服务做分布式集群负载,如何确保A服务的所有集群都能同步公共模块的缓存数据, ...

  9. Springboot整合Ehcache 解决Mybatis二级缓存数据脏读 -详细

    前面有写了一篇关于这个,但是这几天又改进了一点,就单独一篇在详细说明一下 配置 application.properties ,启用Ehcache # Ehcache缓存 spring.cache.t ...

随机推荐

  1. Linux下top命令详解

    Linux下top命令详解 top命令是Linux下常用的性能分析工具,能够实时显示系统中各个进程的资源占用状况,类似于Windows的任务管理器.top是一个动态显示过程,即可以通过用户按键来不断刷 ...

  2. Linux的常用命令(2) - 关机

    关机命令 shutdown‑h now 立即进行关机 shutdown‑r now 现在重新启动计算机 -t sec : -t后面加秒数,即"过几秒后关机" -k      : 不 ...

  3. C++对txt文本进行读写操作

    输入输出,是每个程序员的基本功,尤其是对文本的输入和输出.最近,自己在这方面做了一些总结,不是很全面,希望在以后学习和工作的过程中慢慢补充,积累点点滴滴.P.S. 今天天气不错,雾霾散了,天空晴朗,惠 ...

  4. 详解Linux2.6内核中基于platform机制的驱动模型 (经典)

    [摘要]本文以Linux 2.6.25 内核为例,分析了基于platform总线的驱动模型.首先介绍了Platform总线的基本概念,接着介绍了platform device和platform dri ...

  5. WinCE上BINFS实现详解

    网上不少介绍三星24x0系列的BINFS启动方式实现,有些内容上描述的不是非常全面 下面就WinCE6上的BINFS实现,从基本原理到修改BSP,再到如何烧录启动做一个较全面的讲解 一 BINFS到底 ...

  6. Media Player Classic - HC 源代码分析 1:整体结构

    ===================================================== Media Player Classic - HC 源代码分析系列文章列表: Media P ...

  7. obj-c编程07:异常处理

    好了,到了相对轻松的话题,也是所有语言无可避免的话题:异常的处理. 我们知道对于一些常见的语言,"异常"是逃不开避不掉的主题:C中相对原始的signal或依赖系统异常支持(比如wi ...

  8. 项目群MSP课程最大的特点

    1.课程中间让大家去了解和理解项目群管理的知识体系.方法论,更关注大家的个性化需求: 2.课程中间还会有很多练习和讨论,特别是会请到一些业界在实践MSP的客户,进行他们的实践案例分享.所以从知识到实际 ...

  9. Tomcat的缺省是多少,怎么修改

     Tomcat的缺省端口号是8080. 修改Tomcat端口号: 1.找到Tomcat目录下的conf文件夹 2.进入conf文件夹里面找到server.xml文件 3.打开server.xml文件 ...

  10. ORACLE 本地数据库存储过程 调用远程数据库存储过程

    废话少说,直接切入主题  步骤1:建立一个远程数据库的连接服务名  D:\oracle\ora92\network\admin\tnsnames.ora 添加如下代码:  SDEC =   (DESC ...