一、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. android Gradle的几个基本概念

    什么是Gradle? Gradle是一种依赖管理工具,基于Groovy语言,面向Java应用为主,它抛弃了基于XML的各种繁琐配置,取而代之的是一种基于Groovy的内部领域特定(DSL)语言. Gr ...

  2. android资源库

    原文地址:http://blog.csdn.net/xiechengfa/article/details/38830751 在摸索过程中,GitHub上搜集了很多很棒的Android第三方库,推荐给在 ...

  3. Saiku去掉登录模块

    1.修改applicationContext-saiku-webapp.xml <security:intercept-url pattern="/rest/**" acce ...

  4. Oracle Service Bus白皮书

    Oracle Service Bus简介 面对变幻莫测的市场需求的变化,企业希望通过推进"服务化"提高敏捷性和响应能力:更方便地与客户和合作伙伴交互,更灵活地设计和构建IT基础架构 ...

  5. java工具类(六)根据经纬度计算距离

    Java实现根据经纬度计算距离 在项目开发过程中,需要根据两地经纬度坐标计算两地间距离,所用的工具类如下: Demo1: public static double getDistatce(double ...

  6. Android 之dragger使用

    1.依赖的注入和配置独立于组件之外,注入的对象在一个独立.不耦合的地方初始化,这样在改变注入对象时,我们只需要修改对象的实现方法,而不用大改代码库. 2.依赖可以注入到一个组件中:我们可以注入这些依赖 ...

  7. AndFix使用感想

    AndFix已经使用了一段时间了,但是到AndFix上看了一下,最近2个月都没有更新代码了,有141个issues和3个pull request没人处理,其实AndFix的Contributors就俩 ...

  8. TCP连接建立系列 — 服务端接收SYN段

    本文主要分析:服务器端接收到SYN包时的处理路径. 内核版本:3.6 Author:zhangskd @ csdn blog 接收入口 1. 状态为ESTABLISHED时,用tcp_rcv_esta ...

  9. Android开发技巧——高亮的用户操作指南

    Android开发技巧--高亮的用户操作指南 2015-12-15补记: 发现使用PopupWindow进行遮罩层的显示,在华为P7上会有问题.具体表现为:画出来的高亮部分会偏下.原因为:通过view ...

  10. PowerBI开发 第十篇:R 脚本

    R是一种专门用于数据分析和统计的脚本语言,广泛应用在每一个需要统计和数据分析的领域.PowerBI支持R脚本,只不过,PowerBI Desktop默认没有安装R.在使用R脚本之前,必须向PowerB ...